diff --git a/dist/batch.d.ts b/dist/batch.d.ts new file mode 100644 index 0000000..e32cb17 --- /dev/null +++ b/dist/batch.d.ts @@ -0,0 +1,86 @@ +import type { Provider, BlockTag, Block, TransactionResponse, BaseContract, ContractEventName, EventLog } from 'ethers'; +export interface BatchBlockServiceConstructor { + provider: Provider; + onProgress?: BatchBlockOnProgress; + concurrencySize?: number; + batchSize?: number; + shouldRetry?: boolean; + retryMax?: number; + retryOn?: number; +} +export type BatchBlockOnProgress = ({ percentage, currentIndex, totalIndex, }: { + percentage: number; + currentIndex?: number; + totalIndex?: number; +}) => void; +/** + * Fetch blocks from web3 provider on batches + */ +export declare class BatchBlockService { + provider: Provider; + onProgress?: BatchBlockOnProgress; + concurrencySize: number; + batchSize: number; + shouldRetry: boolean; + retryMax: number; + retryOn: number; + constructor({ provider, onProgress, concurrencySize, batchSize, shouldRetry, retryMax, retryOn, }: BatchBlockServiceConstructor); + getBlock(blockTag: BlockTag): Promise; + createBatchRequest(batchArray: BlockTag[][]): Promise[]; + getBatchBlocks(blocks: BlockTag[]): Promise; +} +/** + * Fetch transactions from web3 provider on batches + */ +export declare class BatchTransactionService { + provider: Provider; + onProgress?: BatchBlockOnProgress; + concurrencySize: number; + batchSize: number; + shouldRetry: boolean; + retryMax: number; + retryOn: number; + constructor({ provider, onProgress, concurrencySize, batchSize, shouldRetry, retryMax, retryOn, }: BatchBlockServiceConstructor); + getTransaction(txHash: string): Promise; + createBatchRequest(batchArray: string[][]): Promise[]; + getBatchTransactions(txs: string[]): Promise; +} +export interface BatchEventServiceConstructor { + provider: Provider; + contract: BaseContract; + onProgress?: BatchEventOnProgress; + concurrencySize?: number; + blocksPerRequest?: number; + shouldRetry?: boolean; + retryMax?: number; + retryOn?: number; +} +export type BatchEventOnProgress = ({ percentage, type, fromBlock, toBlock, count, }: { + percentage: number; + type?: ContractEventName; + fromBlock?: number; + toBlock?: number; + count?: number; +}) => void; +export type EventInput = { + fromBlock: number; + toBlock: number; + type: ContractEventName; +}; +/** + * Fetch events from web3 provider on bulk + */ +export declare class BatchEventsService { + provider: Provider; + contract: BaseContract; + onProgress?: BatchEventOnProgress; + concurrencySize: number; + blocksPerRequest: number; + shouldRetry: boolean; + retryMax: number; + retryOn: number; + constructor({ provider, contract, onProgress, concurrencySize, blocksPerRequest, shouldRetry, retryMax, retryOn, }: BatchEventServiceConstructor); + getPastEvents({ fromBlock, toBlock, type }: EventInput): Promise; + createBatchRequest(batchArray: EventInput[]): Promise[]; + getBatchEvents({ fromBlock, toBlock, type }: EventInput): Promise; +} diff --git a/dist/data.d.ts b/dist/data.d.ts new file mode 100644 index 0000000..9a46b52 --- /dev/null +++ b/dist/data.d.ts @@ -0,0 +1,24 @@ +import { AsyncZippable, Unzipped } from 'fflate'; +import { BaseEvents, MinimalEvents } from './events'; +export declare function existsAsync(fileOrDir: string): Promise; +export declare function zipAsync(file: AsyncZippable): Promise; +export declare function unzipAsync(data: Uint8Array): Promise; +export declare function saveUserFile({ fileName, userDirectory, dataString, }: { + fileName: string; + userDirectory: string; + dataString: string; +}): Promise; +export declare function loadSavedEvents({ name, userDirectory, deployedBlock, }: { + name: string; + userDirectory: string; + deployedBlock: number; +}): Promise>; +export declare function download({ name, cacheDirectory }: { + name: string; + cacheDirectory: string; +}): Promise; +export declare function loadCachedEvents({ name, cacheDirectory, deployedBlock, }: { + name: string; + cacheDirectory: string; + deployedBlock: number; +}): Promise>; diff --git a/dist/deposits.d.ts b/dist/deposits.d.ts new file mode 100644 index 0000000..ae2ca21 --- /dev/null +++ b/dist/deposits.d.ts @@ -0,0 +1,74 @@ +import type { NetIdType } from './networkConfig'; +export type DepositType = { + currency: string; + amount: string; + netId: NetIdType; +}; +export type createDepositParams = { + nullifier: bigint; + secret: bigint; +}; +export type createDepositObject = { + preimage: Uint8Array; + noteHex: string; + commitment: bigint; + commitmentHex: string; + nullifierHash: bigint; + nullifierHex: string; +}; +export type createNoteParams = DepositType & { + nullifier?: bigint; + secret?: bigint; +}; +export type parsedNoteExec = DepositType & { + note: string; +}; +export type depositTx = { + from: string; + transactionHash: string; +}; +export type withdrawalTx = { + to: string; + transactionHash: string; +}; +export declare function createDeposit({ nullifier, secret }: createDepositParams): Promise; +export interface DepositConstructor { + currency: string; + amount: string; + netId: NetIdType; + nullifier: bigint; + secret: bigint; + note: string; + noteHex: string; + invoice: string; + commitmentHex: string; + nullifierHex: string; +} +export declare class Deposit { + currency: string; + amount: string; + netId: NetIdType; + nullifier: bigint; + secret: bigint; + note: string; + noteHex: string; + invoice: string; + commitmentHex: string; + nullifierHex: string; + constructor({ currency, amount, netId, nullifier, secret, note, noteHex, invoice, commitmentHex, nullifierHex, }: DepositConstructor); + toString(): string; + static createNote({ currency, amount, netId, nullifier, secret }: createNoteParams): Promise; + static parseNote(noteString: string): Promise; +} +export type parsedInvoiceExec = DepositType & { + commitment: string; +}; +export declare class Invoice { + currency: string; + amount: string; + netId: NetIdType; + commitment: string; + invoice: string; + constructor(invoiceString: string); + toString(): string; +} diff --git a/dist/encryptedNotes.d.ts b/dist/encryptedNotes.d.ts new file mode 100644 index 0000000..4e20fe0 --- /dev/null +++ b/dist/encryptedNotes.d.ts @@ -0,0 +1,48 @@ +import { EthEncryptedData } from '@metamask/eth-sig-util'; +import { Echoer } from '@tornado/contracts'; +import { Wallet } from 'ethers'; +import { EchoEvents, EncryptedNotesEvents } from './events'; +import type { NetIdType } from './networkConfig'; +export interface NoteToEncrypt { + address: string; + noteHex: string; +} +export interface DecryptedNotes { + blockNumber: number; + address: string; + noteHex: string; +} +export declare function packEncryptedMessage({ nonce, ephemPublicKey, ciphertext }: EthEncryptedData): string; +export declare function unpackEncryptedMessage(encryptedMessage: string): EthEncryptedData & { + messageBuff: string; +}; +export interface NoteAccountConstructor { + netId: NetIdType; + blockNumber?: number; + recoveryKey?: string; + Echoer: Echoer; +} +export declare class NoteAccount { + netId: NetIdType; + blockNumber?: number; + recoveryKey: string; + recoveryAddress: string; + recoveryPublicKey: string; + Echoer: Echoer; + constructor({ netId, blockNumber, recoveryKey, Echoer }: NoteAccountConstructor); + /** + * Intends to mock eth_getEncryptionPublicKey behavior from MetaMask + * In order to make the recoveryKey retrival from Echoer possible from the bare private key + */ + static getWalletPublicKey(wallet: Wallet): string; + getEncryptedAccount(walletPublicKey: string): { + encryptedData: EthEncryptedData; + data: string; + }; + /** + * Decrypt Echoer backuped note encryption account with private keys + */ + decryptAccountsWithWallet(wallet: Wallet, events: EchoEvents[]): NoteAccount[]; + decryptNotes(events: EncryptedNotesEvents[]): DecryptedNotes[]; + encryptNote({ address, noteHex }: NoteToEncrypt): string; +} diff --git a/dist/events/base.d.ts b/dist/events/base.d.ts new file mode 100644 index 0000000..910f907 --- /dev/null +++ b/dist/events/base.d.ts @@ -0,0 +1,191 @@ +import { BaseContract, Provider, EventLog, ContractEventName } from 'ethers'; +import type { Tornado, TornadoRouter, TornadoProxyLight, Governance, RelayerRegistry, Echoer } from '@tornado/contracts'; +import { BatchEventsService, BatchBlockService, BatchTransactionService, BatchEventOnProgress, BatchBlockOnProgress } from '../batch'; +import { fetchDataOptions } from '../providers'; +import type { NetIdType } from '../networkConfig'; +import type { BaseEvents, MinimalEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, AllGovernanceEvents, RegistersEvents, EchoEvents } from './types'; +export declare const DEPOSIT = "deposit"; +export declare const WITHDRAWAL = "withdrawal"; +export type BaseEventsServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + contract: BaseContract; + type?: string; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export type BatchGraphOnProgress = ({ type, fromBlock, toBlock, count, }: { + type?: ContractEventName; + fromBlock?: number; + toBlock?: number; + count?: number; +}) => void; +export type BaseGraphParams = { + graphApi: string; + subgraphName: string; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +}; +export declare class BaseEventsService { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + contract: BaseContract; + type: string; + deployedBlock: number; + batchEventsService: BatchEventsService; + fetchDataOptions?: fetchDataOptions; + constructor({ netId, provider, graphApi, subgraphName, contract, type, deployedBlock, fetchDataOptions, }: BaseEventsServiceConstructor); + getInstanceName(): string; + getType(): string; + getGraphMethod(): string; + getGraphParams(): BaseGraphParams; + updateEventProgress({ percentage, type, fromBlock, toBlock, count }: Parameters[0]): void; + updateBlockProgress({ percentage, currentIndex, totalIndex }: Parameters[0]): void; + updateTransactionProgress({ percentage, currentIndex, totalIndex }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + formatEvents(events: EventLog[]): Promise; + /** + * Get saved or cached events + */ + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + getSavedEvents(): Promise>; + /** + * Get latest events + */ + getEventsFromGraph({ fromBlock, methodName, }: { + fromBlock: number; + methodName?: string; + }): Promise>; + getEventsFromRpc({ fromBlock, toBlock, }: { + fromBlock: number; + toBlock?: number; + }): Promise>; + getLatestEvents({ fromBlock }: { + fromBlock: number; + }): Promise>; + validateEvents({ events, lastBlock }: BaseEvents): void; + /** + * Handle saving events + */ + saveEvents({ events, lastBlock }: BaseEvents): Promise; + /** + * Trigger saving and receiving latest events + */ + updateEvents(): Promise<{ + events: EventType[]; + lastBlock: number | null; + }>; +} +export type BaseDepositsServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + Tornado: Tornado; + type: string; + amount: string; + currency: string; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export type DepositsGraphParams = BaseGraphParams & { + amount: string; + currency: string; +}; +export declare class BaseDepositsService extends BaseEventsService { + amount: string; + currency: string; + batchTransactionService: BatchTransactionService; + batchBlockService: BatchBlockService; + constructor({ netId, provider, graphApi, subgraphName, Tornado, type, amount, currency, deployedBlock, fetchDataOptions, }: BaseDepositsServiceConstructor); + getInstanceName(): string; + getGraphMethod(): string; + getGraphParams(): DepositsGraphParams; + formatEvents(events: EventLog[]): Promise<(DepositsEvents | WithdrawalsEvents)[]>; + validateEvents({ events }: { + events: (DepositsEvents | WithdrawalsEvents)[]; + }): void; +} +export type BaseEchoServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + Echoer: Echoer; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export declare class BaseEchoService extends BaseEventsService { + constructor({ netId, provider, graphApi, subgraphName, Echoer, deployedBlock, fetchDataOptions, }: BaseEchoServiceConstructor); + getInstanceName(): string; + getType(): string; + getGraphMethod(): string; + formatEvents(events: EventLog[]): Promise; + getEventsFromGraph({ fromBlock }: { + fromBlock: number; + }): Promise>; +} +export type BaseEncryptedNotesServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + Router: TornadoRouter | TornadoProxyLight; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export declare class BaseEncryptedNotesService extends BaseEventsService { + constructor({ netId, provider, graphApi, subgraphName, Router, deployedBlock, fetchDataOptions, }: BaseEncryptedNotesServiceConstructor); + getInstanceName(): string; + getType(): string; + getGraphMethod(): string; + formatEvents(events: EventLog[]): Promise; +} +export type BaseGovernanceServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + Governance: Governance; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export declare class BaseGovernanceService extends BaseEventsService { + batchTransactionService: BatchTransactionService; + constructor({ netId, provider, graphApi, subgraphName, Governance, deployedBlock, fetchDataOptions, }: BaseGovernanceServiceConstructor); + getInstanceName(): string; + getType(): string; + getGraphMethod(): string; + formatEvents(events: EventLog[]): Promise; + getEventsFromGraph({ fromBlock }: { + fromBlock: number; + }): Promise>; +} +export type BaseRegistryServiceConstructor = { + netId: NetIdType; + provider: Provider; + graphApi?: string; + subgraphName?: string; + RelayerRegistry: RelayerRegistry; + deployedBlock?: number; + fetchDataOptions?: fetchDataOptions; +}; +export declare class BaseRegistryService extends BaseEventsService { + constructor({ netId, provider, graphApi, subgraphName, RelayerRegistry, deployedBlock, fetchDataOptions, }: BaseRegistryServiceConstructor); + getInstanceName(): string; + getType(): string; + getGraphMethod(): string; + formatEvents(events: EventLog[]): Promise<{ + ensName: any; + relayerAddress: any; + blockNumber: number; + logIndex: number; + transactionHash: string; + }[]>; + fetchRelayers(): Promise; +} diff --git a/dist/events/index.d.ts b/dist/events/index.d.ts new file mode 100644 index 0000000..c386db6 --- /dev/null +++ b/dist/events/index.d.ts @@ -0,0 +1,3 @@ +export * from './types'; +export * from './base'; +export * from './node'; diff --git a/dist/events/node.d.ts b/dist/events/node.d.ts new file mode 100644 index 0000000..331204e --- /dev/null +++ b/dist/events/node.d.ts @@ -0,0 +1,76 @@ +import { BatchBlockOnProgress, BatchEventOnProgress } from '../batch'; +import { BaseDepositsService, BaseEncryptedNotesService, BaseGovernanceService, BaseRegistryService, BaseDepositsServiceConstructor, BaseEncryptedNotesServiceConstructor, BaseGovernanceServiceConstructor, BaseRegistryServiceConstructor, BaseEchoServiceConstructor, BaseEchoService } from './base'; +import type { BaseEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, RegistersEvents, AllGovernanceEvents, EchoEvents } from './types'; +export type NodeDepositsServiceConstructor = BaseDepositsServiceConstructor & { + cacheDirectory?: string; + userDirectory?: string; +}; +export declare class NodeDepositsService extends BaseDepositsService { + cacheDirectory?: string; + userDirectory?: string; + constructor({ netId, provider, graphApi, subgraphName, Tornado, type, amount, currency, deployedBlock, fetchDataOptions, cacheDirectory, userDirectory, }: NodeDepositsServiceConstructor); + updateEventProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateTransactionProgress({ currentIndex, totalIndex }: Parameters[0]): void; + updateBlockProgress({ currentIndex, totalIndex }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + saveEvents({ events, lastBlock }: BaseEvents): Promise; +} +export type NodeEchoServiceConstructor = BaseEchoServiceConstructor & { + cacheDirectory?: string; + userDirectory?: string; +}; +export declare class NodeEchoService extends BaseEchoService { + cacheDirectory?: string; + userDirectory?: string; + constructor({ netId, provider, graphApi, subgraphName, Echoer, deployedBlock, fetchDataOptions, cacheDirectory, userDirectory, }: NodeEchoServiceConstructor); + updateEventProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + saveEvents({ events, lastBlock }: BaseEvents): Promise; +} +export type NodeEncryptedNotesServiceConstructor = BaseEncryptedNotesServiceConstructor & { + cacheDirectory?: string; + userDirectory?: string; +}; +export declare class NodeEncryptedNotesService extends BaseEncryptedNotesService { + cacheDirectory?: string; + userDirectory?: string; + constructor({ netId, provider, graphApi, subgraphName, Router, deployedBlock, fetchDataOptions, cacheDirectory, userDirectory, }: NodeEncryptedNotesServiceConstructor); + updateEventProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + saveEvents({ events, lastBlock }: BaseEvents): Promise; +} +export type NodeGovernanceServiceConstructor = BaseGovernanceServiceConstructor & { + cacheDirectory?: string; + userDirectory?: string; +}; +export declare class NodeGovernanceService extends BaseGovernanceService { + cacheDirectory?: string; + userDirectory?: string; + constructor({ netId, provider, graphApi, subgraphName, Governance, deployedBlock, fetchDataOptions, cacheDirectory, userDirectory, }: NodeGovernanceServiceConstructor); + updateEventProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateTransactionProgress({ currentIndex, totalIndex }: Parameters[0]): void; + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + saveEvents({ events, lastBlock }: BaseEvents): Promise; +} +export type NodeRegistryServiceConstructor = BaseRegistryServiceConstructor & { + cacheDirectory?: string; + userDirectory?: string; +}; +export declare class NodeRegistryService extends BaseRegistryService { + cacheDirectory?: string; + userDirectory?: string; + constructor({ netId, provider, graphApi, subgraphName, RelayerRegistry, deployedBlock, fetchDataOptions, cacheDirectory, userDirectory, }: NodeRegistryServiceConstructor); + updateEventProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + updateGraphProgress({ type, fromBlock, toBlock, count }: Parameters[0]): void; + getEventsFromDB(): Promise>; + getEventsFromCache(): Promise>; + saveEvents({ events, lastBlock }: BaseEvents): Promise; +} diff --git a/dist/events/types.d.ts b/dist/events/types.d.ts new file mode 100644 index 0000000..51cadee --- /dev/null +++ b/dist/events/types.d.ts @@ -0,0 +1,62 @@ +import { RelayerParams } from '../relayerClient'; +export interface BaseEvents { + events: T[]; + lastBlock: number | null; +} +export interface BaseGraphEvents { + events: T[]; + lastSyncBlock: number; +} +export interface MinimalEvents { + blockNumber: number; + logIndex: number; + transactionHash: string; +} +export type GovernanceEvents = MinimalEvents & { + event: string; +}; +export type GovernanceProposalCreatedEvents = GovernanceEvents & { + id: number; + proposer: string; + target: string; + startTime: number; + endTime: number; + description: string; +}; +export type GovernanceVotedEvents = GovernanceEvents & { + proposalId: number; + voter: string; + support: boolean; + votes: string; + from: string; + input: string; +}; +export type GovernanceDelegatedEvents = GovernanceEvents & { + account: string; + delegateTo: string; +}; +export type GovernanceUndelegatedEvents = GovernanceEvents & { + account: string; + delegateFrom: string; +}; +export type AllGovernanceEvents = GovernanceProposalCreatedEvents | GovernanceVotedEvents | GovernanceDelegatedEvents | GovernanceUndelegatedEvents; +export type RegistersEvents = MinimalEvents & RelayerParams; +export type DepositsEvents = MinimalEvents & { + commitment: string; + leafIndex: number; + timestamp: number; + from: string; +}; +export type WithdrawalsEvents = MinimalEvents & { + nullifierHash: string; + to: string; + fee: string; + timestamp: number; +}; +export type EchoEvents = MinimalEvents & { + address: string; + encryptedAccount: string; +}; +export type EncryptedNotesEvents = MinimalEvents & { + encryptedNote: string; +}; diff --git a/dist/fees.d.ts b/dist/fees.d.ts new file mode 100644 index 0000000..e0703e0 --- /dev/null +++ b/dist/fees.d.ts @@ -0,0 +1,45 @@ +import type { BigNumberish, TransactionLike } from 'ethers'; +import { OvmGasPriceOracle } from './typechain'; +/** + * Example: + * + * amountInWei (0.1 ETH) * tokenDecimals (18) * tokenPriceInWei (0.0008) = 125 TOKEN + */ +export declare function convertETHToTokenAmount(amountInWei: BigNumberish, tokenPriceInWei: BigNumberish, tokenDecimals?: number): bigint; +export interface RelayerFeeParams { + gasPrice: BigNumberish; + gasLimit?: BigNumberish; + l1Fee?: BigNumberish; + denomination: BigNumberish; + ethRefund: BigNumberish; + tokenPriceInWei: BigNumberish; + tokenDecimals: number; + relayerFeePercent?: number; + isEth?: boolean; + premiumPercent?: number; +} +export declare class TornadoFeeOracle { + ovmGasPriceOracle?: OvmGasPriceOracle; + constructor(ovmGasPriceOracle?: OvmGasPriceOracle); + /** + * Calculate L1 fee for op-stack chains + * + * This is required since relayers would pay the full transaction fees for users + */ + fetchL1OptimismFee(tx?: TransactionLike): Promise; + /** + * We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal + * So we default with 1M gas which is enough for two or three swaps + * Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI + */ + defaultEthRefund(gasPrice?: BigNumberish, gasLimit?: BigNumberish): bigint; + /** + * Calculates token amount for required ethRefund purchases required to calculate fees + */ + calculateTokenAmount(ethRefund: BigNumberish, tokenPriceInEth: BigNumberish, tokenDecimals?: number): bigint; + /** + * Warning: For tokens you need to check if the fees are above denomination + * (Usually happens for small denomination pool or if the gas price is high) + */ + calculateRelayerFee({ gasPrice, gasLimit, l1Fee, denomination, ethRefund, tokenPriceInWei, tokenDecimals, relayerFeePercent, isEth, premiumPercent, }: RelayerFeeParams): bigint; +} diff --git a/dist/graphql/index.d.ts b/dist/graphql/index.d.ts new file mode 100644 index 0000000..c9832ae --- /dev/null +++ b/dist/graphql/index.d.ts @@ -0,0 +1,266 @@ +import { fetchDataOptions } from '../providers'; +import type { BaseGraphEvents, RegistersEvents, DepositsEvents, WithdrawalsEvents, EncryptedNotesEvents, BatchGraphOnProgress, EchoEvents, AllGovernanceEvents } from '../events'; +export * from './queries'; +export type queryGraphParams = { + graphApi: string; + subgraphName: string; + query: string; + variables?: { + [key: string]: string | number; + }; + fetchDataOptions?: fetchDataOptions; +}; +export declare function queryGraph({ graphApi, subgraphName, query, variables, fetchDataOptions, }: queryGraphParams): Promise; +export interface GraphStatistic { + deposits: { + index: string; + timestamp: string; + blockNumber: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getStatisticParams { + graphApi: string; + subgraphName: string; + currency: string; + amount: string; + fetchDataOptions?: fetchDataOptions; +} +export interface getStatisticReturns { + events: { + timestamp: number; + leafIndex: number; + blockNumber: number; + }[]; + lastSyncBlock: null | number; +} +export declare function getStatistic({ graphApi, subgraphName, currency, amount, fetchDataOptions, }: getStatisticParams): Promise; +export interface GraphMeta { + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getMetaParams { + graphApi: string; + subgraphName: string; + fetchDataOptions?: fetchDataOptions; +} +export interface getMetaReturns { + lastSyncBlock: null | number; + hasIndexingErrors: null | boolean; +} +export declare function getMeta({ graphApi, subgraphName, fetchDataOptions }: getMetaParams): Promise; +export interface GraphRegisters { + relayers: { + id: string; + address: string; + ensName: string; + blockRegistration: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getRegistersParams { + graphApi: string; + subgraphName: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions, }: getRegistersParams): Promise; +export declare function getAllRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions, onProgress, }: getRegistersParams): Promise>; +export interface GraphDeposits { + deposits: { + id: string; + blockNumber: string; + commitment: string; + index: string; + timestamp: string; + from: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getDepositsParams { + graphApi: string; + subgraphName: string; + currency: string; + amount: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions, }: getDepositsParams): Promise; +export declare function getAllDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions, onProgress, }: getDepositsParams): Promise>; +export interface GraphWithdrawals { + withdrawals: { + id: string; + blockNumber: string; + nullifier: string; + to: string; + fee: string; + timestamp: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getWithdrawalParams { + graphApi: string; + subgraphName: string; + currency: string; + amount: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions, }: getWithdrawalParams): Promise; +export declare function getAllWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions, onProgress, }: getWithdrawalParams): Promise>; +export interface GraphNoteAccounts { + noteAccounts: { + id: string; + index: string; + address: string; + encryptedAccount: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getNoteAccountsParams { + graphApi: string; + subgraphName: string; + address: string; + fetchDataOptions?: fetchDataOptions; +} +export interface getNoteAccountsReturns { + events: { + id: string; + index: string; + address: string; + encryptedAccount: string; + }[]; + lastSyncBlock: null | number; +} +export declare function getNoteAccounts({ graphApi, subgraphName, address, fetchDataOptions, }: getNoteAccountsParams): Promise; +export interface GraphEchoEvents { + noteAccounts: { + id: string; + blockNumber: string; + address: string; + encryptedAccount: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getGraphEchoEventsParams { + graphApi: string; + subgraphName: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions, }: getGraphEchoEventsParams): Promise; +export declare function getAllGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions, onProgress, }: getGraphEchoEventsParams): Promise>; +export interface GraphEncryptedNotes { + encryptedNotes: { + blockNumber: string; + index: string; + transactionHash: string; + encryptedNote: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getEncryptedNotesParams { + graphApi: string; + subgraphName: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions, }: getEncryptedNotesParams): Promise; +export declare function getAllEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions, onProgress, }: getEncryptedNotesParams): Promise>; +export interface GraphGovernanceEvents { + proposals: { + blockNumber: number; + logIndex: number; + transactionHash: string; + proposalId: number; + proposer: string; + target: string; + startTime: number; + endTime: number; + description: string; + }[]; + votes: { + blockNumber: number; + logIndex: number; + transactionHash: string; + proposalId: number; + voter: string; + support: boolean; + votes: string; + from: string; + input: string; + }[]; + delegates: { + blockNumber: number; + logIndex: number; + transactionHash: string; + account: string; + delegateTo: string; + }[]; + undelegates: { + blockNumber: number; + logIndex: number; + transactionHash: string; + account: string; + delegateFrom: string; + }[]; + _meta: { + block: { + number: number; + }; + hasIndexingErrors: boolean; + }; +} +export interface getGovernanceEventsParams { + graphApi: string; + subgraphName: string; + fromBlock: number; + fetchDataOptions?: fetchDataOptions; + onProgress?: BatchGraphOnProgress; +} +export declare function getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions, }: getGovernanceEventsParams): Promise; +export declare function getAllGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions, onProgress, }: getGovernanceEventsParams): Promise>; diff --git a/dist/graphql/queries.d.ts b/dist/graphql/queries.d.ts new file mode 100644 index 0000000..26f8777 --- /dev/null +++ b/dist/graphql/queries.d.ts @@ -0,0 +1,10 @@ +export declare const GET_STATISTIC = "\n query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) {\n deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) {\n index\n timestamp\n blockNumber\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const _META = "\n query getMeta {\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_REGISTERED = "\n query getRegistered($first: Int, $fromBlock: Int) {\n relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: {\n blockRegistration_gte: $fromBlock\n }) {\n id\n address\n ensName\n blockRegistration\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_DEPOSITS = "\n query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) {\n deposits(first: $first, orderBy: index, orderDirection: asc, where: { \n amount: $amount,\n currency: $currency,\n blockNumber_gte: $fromBlock\n }) {\n id\n blockNumber\n commitment\n index\n timestamp\n from\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_WITHDRAWALS = "\n query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) {\n withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { \n currency: $currency,\n amount: $amount,\n blockNumber_gte: $fromBlock\n }) {\n id\n blockNumber\n nullifier\n to\n fee\n timestamp\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_NOTE_ACCOUNTS = "\n query getNoteAccount($address: String!) {\n noteAccounts(where: { address: $address }) {\n id\n index\n address\n encryptedAccount\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_ECHO_EVENTS = "\n query getNoteAccounts($first: Int, $fromBlock: Int) {\n noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n id\n blockNumber\n address\n encryptedAccount\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_ENCRYPTED_NOTES = "\n query getEncryptedNotes($first: Int, $fromBlock: Int) {\n encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n blockNumber\n index\n transactionHash\n encryptedNote\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_GOVERNANCE_EVENTS = "\n query getGovernanceEvents($first: Int, $fromBlock: Int) {\n proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n blockNumber\n logIndex\n transactionHash\n proposalId\n proposer\n target\n startTime\n endTime\n description\n }\n votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n blockNumber\n logIndex\n transactionHash\n proposalId\n voter\n support\n votes\n from\n input\n }\n delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n blockNumber\n logIndex\n transactionHash\n account\n delegateTo\n }\n undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) {\n blockNumber\n logIndex\n transactionHash\n account\n delegateFrom\n }\n _meta {\n block {\n number\n }\n hasIndexingErrors\n }\n }\n"; +export declare const GET_GOVERNANCE_APY = "\n stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) {\n id\n date\n dailyAmountBurned\n }\n"; diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..67793bd --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,22 @@ +export * from './events'; +export * from './graphql'; +export * from './schemas'; +export * from './typechain'; +export * from './batch'; +export * from './data'; +export * from './deposits'; +export * from './encryptedNotes'; +export * from './fees'; +export * from './merkleTree'; +export * from './mimc'; +export * from './multicall'; +export * from './networkConfig'; +export * from './parser'; +export * from './pedersen'; +export * from './prices'; +export * from './providers'; +export * from './relayerClient'; +export * from './tokens'; +export * from './treeCache'; +export * from './utils'; +export * from './websnark'; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..1927152 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,7997 @@ +'use strict'; + +var ethers = require('ethers'); +var crossFetch = require('cross-fetch'); +var httpProxyAgent = require('http-proxy-agent'); +var httpsProxyAgent = require('https-proxy-agent'); +var socksProxyAgent = require('socks-proxy-agent'); +var crypto$1 = require('crypto'); +var BN = require('bn.js'); +var Table = require('cli-table3'); +var moment = require('moment'); +var path = require('path'); +var promises = require('fs/promises'); +var fflate = require('fflate'); +var Ajv = require('ajv'); +var circomlibjs = require('circomlibjs'); +var ethSigUtil = require('@metamask/eth-sig-util'); +var worker_threads = require('worker_threads'); +var fixedMerkleTree = require('@tornado/fixed-merkle-tree'); +var commander = require('commander'); +var BloomFilter = require('bloomfilter.js'); +var websnarkUtils = require('@tornado/websnark/src/utils'); +var websnarkGroth = require('@tornado/websnark/src/groth16'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var websnarkUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(websnarkUtils); + +const _abi$6 = [ + { + constant: true, + inputs: [ + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "supportsInterface", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "pure", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + }, + { + internalType: "string", + name: "value", + type: "string" + } + ], + name: "setText", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "interfaceImplementer", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentTypes", + type: "uint256" + } + ], + name: "ABI", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + }, + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "setPubkey", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "setContenthash", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "addr", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "setAuthorisation", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + } + ], + name: "text", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentType", + type: "uint256" + }, + { + internalType: "bytes", + name: "data", + type: "bytes" + } + ], + name: "setABI", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "name", + type: "string" + } + ], + name: "setName", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + internalType: "bytes", + name: "a", + type: "bytes" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "contenthash", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "pubkey", + outputs: [ + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "a", + type: "address" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "setInterface", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + } + ], + name: "addr", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + }, + { + internalType: "address", + name: "", + type: "address" + }, + { + internalType: "address", + name: "", + type: "address" + } + ], + name: "authorisations", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + payable: false, + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "target", + type: "address" + }, + { + indexed: false, + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "AuthorisationChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "indexedKey", + type: "string" + }, + { + indexed: false, + internalType: "string", + name: "key", + type: "string" + } + ], + name: "TextChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "PubkeyChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "name", + type: "string" + } + ], + name: "NameChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + indexed: false, + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "InterfaceChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "ContenthashChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "address", + name: "a", + type: "address" + } + ], + name: "AddrChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + indexed: false, + internalType: "bytes", + name: "newAddress", + type: "bytes" + } + ], + name: "AddressChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "uint256", + name: "contentType", + type: "uint256" + } + ], + name: "ABIChanged", + type: "event" + } +]; +class ENS__factory { + static createInterface() { + return new ethers.Interface(_abi$6); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$6, runner); + } +} +ENS__factory.abi = _abi$6; + +const _abi$5 = [ + { + constant: true, + inputs: [], + name: "totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "_totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "who", + type: "address" + } + ], + name: "balanceOf", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "symbol", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transfer", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "spender", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Approval", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "from", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "to", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Transfer", + type: "event" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + } + ], + name: "allowance", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "from", + type: "address" + }, + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transferFrom", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "approve", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + } + ], + name: "nonces", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "amount", + type: "uint256" + }, + { + internalType: "uint256", + name: "deadline", + type: "uint256" + }, + { + internalType: "uint8", + name: "v", + type: "uint8" + }, + { + internalType: "bytes32", + name: "r", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "s", + type: "bytes32" + } + ], + name: "permit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class ERC20__factory { + static createInterface() { + return new ethers.Interface(_abi$5); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$5, runner); + } +} +ERC20__factory.abi = _abi$5; + +const _abi$4 = [ + { + inputs: [], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "GAS_UNIT", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_derivationThresold", + type: "uint32" + } + ], + name: "changeDerivationThresold", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasUnit", + type: "uint32" + } + ], + name: "changeGasUnit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_heartbeat", + type: "uint32" + } + ], + name: "changeHeartbeat", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + name: "changeOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "derivationThresold", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "heartbeat", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxPriorityFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "pastGasPrice", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasPrice", + type: "uint32" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "timestamp", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + } +]; +class GasPriceOracle__factory { + static createInterface() { + return new ethers.Interface(_abi$4); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$4, runner); + } +} +GasPriceOracle__factory.abi = _abi$4; + +const _abi$3 = [ + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes[]", + name: "returnData", + type: "bytes[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3Value[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3Value", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "blockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [], + name: "getBasefee", + outputs: [ + { + internalType: "uint256", + name: "basefee", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + name: "getBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getBlockNumber", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getChainId", + outputs: [ + { + internalType: "uint256", + name: "chainid", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockCoinbase", + outputs: [ + { + internalType: "address", + name: "coinbase", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockDifficulty", + outputs: [ + { + internalType: "uint256", + name: "difficulty", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockGasLimit", + outputs: [ + { + internalType: "uint256", + name: "gaslimit", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockTimestamp", + outputs: [ + { + internalType: "uint256", + name: "timestamp", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "addr", + type: "address" + } + ], + name: "getEthBalance", + outputs: [ + { + internalType: "uint256", + name: "balance", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getLastBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryAggregate", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryBlockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + } +]; +class Multicall__factory { + static createInterface() { + return new ethers.Interface(_abi$3); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$3, runner); + } +} +Multicall__factory.abi = _abi$3; + +const _abi$2 = [ + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + }, + { + internalType: "contract IOracle[]", + name: "existingOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + }, + { + internalType: "contract IERC20[]", + name: "existingConnectors", + type: "address[]" + }, + { + internalType: "contract IERC20", + name: "wBase", + type: "address" + }, + { + internalType: "address", + name: "owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "ArraysLengthMismatch", + type: "error" + }, + { + inputs: [], + name: "ConnectorAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "InvalidOracleTokenKind", + type: "error" + }, + { + inputs: [], + name: "OracleAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "SameTokens", + type: "error" + }, + { + inputs: [], + name: "TooBigThreshold", + type: "error" + }, + { + inputs: [], + name: "UnknownConnector", + type: "error" + }, + { + inputs: [], + name: "UnknownOracle", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract MultiWrapper", + name: "multiWrapper", + type: "address" + } + ], + name: "MultiWrapperUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "addConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "addOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "connectors", + outputs: [ + { + internalType: "contract IERC20[]", + name: "allConnectors", + type: "address[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + } + ], + name: "getRate", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + } + ], + name: "getRateToEth", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "multiWrapper", + outputs: [ + { + internalType: "contract MultiWrapper", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "oracles", + outputs: [ + { + internalType: "contract IOracle[]", + name: "allOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "removeConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "removeOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + } + ], + name: "setMultiWrapper", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OffchainOracle__factory { + static createInterface() { + return new ethers.Interface(_abi$2); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$2, runner); + } +} +OffchainOracle__factory.abi = _abi$2; + +const _abi$1 = [ + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "DecimalsUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "GasPriceUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "L1BaseFeeUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "OverheadUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "ScalarUpdated", + type: "event" + }, + { + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1Fee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1GasUsed", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "l1BaseFee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "overhead", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "scalar", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_decimals", + type: "uint256" + } + ], + name: "setDecimals", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_gasPrice", + type: "uint256" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_baseFee", + type: "uint256" + } + ], + name: "setL1BaseFee", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_overhead", + type: "uint256" + } + ], + name: "setOverhead", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_scalar", + type: "uint256" + } + ], + name: "setScalar", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OvmGasPriceOracle__factory { + static createInterface() { + return new ethers.Interface(_abi$1); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi$1, runner); + } +} +OvmGasPriceOracle__factory.abi = _abi$1; + +const _abi = [ + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + internalType: "address[]", + name: "addresses", + type: "address[]" + } + ], + name: "getNames", + outputs: [ + { + internalType: "string[]", + name: "r", + type: "string[]" + } + ], + stateMutability: "view", + type: "function" + } +]; +class ReverseRecords__factory { + static createInterface() { + return new ethers.Interface(_abi); + } + static connect(address, runner) { + return new ethers.Contract(address, _abi, runner); + } +} +ReverseRecords__factory.abi = _abi; + +var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + ENS__factory: ENS__factory, + ERC20__factory: ERC20__factory, + GasPriceOracle__factory: GasPriceOracle__factory, + Multicall__factory: Multicall__factory, + OffchainOracle__factory: OffchainOracle__factory, + OvmGasPriceOracle__factory: OvmGasPriceOracle__factory, + ReverseRecords__factory: ReverseRecords__factory +}); + +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; +const crypto = isNode ? crypto$1.webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new BN(bytes, 16, "le"); +} +function leInt2Buff(bigint) { + return Uint8Array.from(new BN(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + +var __async$e = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function multicall(Multicall2, calls) { + return __async$e(this, null, function* () { + const calldata = calls.map((call) => { + var _a, _b, _c; + const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; + const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; + return { + target, + callData: callInterface.encodeFunctionData(call.name, call.params), + allowFailure: (_c = call.allowFailure) != null ? _c : false + }; + }); + const returnData = yield Multicall2.aggregate3.staticCall(calldata); + const res = returnData.map((call, i) => { + var _a; + const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; + const [result, data] = call; + const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; + return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; + }); + return res; + }); +} + +var __defProp$5 = Object.defineProperty; +var __defProps$4 = Object.defineProperties; +var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols; +var __getProtoOf$1 = Object.getPrototypeOf; +var __hasOwnProp$5 = Object.prototype.hasOwnProperty; +var __propIsEnum$5 = Object.prototype.propertyIsEnumerable; +var __reflectGet$1 = Reflect.get; +var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$5 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + if (__getOwnPropSymbols$5) + for (var prop of __getOwnPropSymbols$5(b)) { + if (__propIsEnum$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b)); +var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); +var __async$d = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +const fetch = crossFetch; +function getHttpAgent({ + fetchUrl, + proxyUrl, + torPort, + retry +}) { + if (torPort) { + return new socksProxyAgent.SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); + } + if (!proxyUrl) { + return; + } + const isHttps = fetchUrl.includes("https://"); + if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { + return new socksProxyAgent.SocksProxyAgent(proxyUrl); + } + if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { + if (isHttps) { + return new httpsProxyAgent.HttpsProxyAgent(proxyUrl); + } + return new httpProxyAgent.HttpProxyAgent(proxyUrl); + } +} +function fetchData(_0) { + return __async$d(this, arguments, function* (url, options = {}) { + var _a, _b, _c; + const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; + const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; + const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; + let retry = 0; + let errorObject; + if (!options.method) { + if (!options.body) { + options.method = "GET"; + } else { + options.method = "POST"; + } + } + if (!options.headers) { + options.headers = {}; + } + if (isNode && !options.headers["User-Agent"]) { + options.headers["User-Agent"] = userAgent; + } + while (retry < MAX_RETRY + 1) { + let timeout; + if (!options.signal && options.timeout) { + const controller = new AbortController(); + options.signal = controller.signal; + timeout = setTimeout(() => { + controller.abort(); + }, options.timeout); + } + if (!options.agent && isNode && (options.proxy || options.torPort)) { + options.agent = getHttpAgent({ + fetchUrl: url, + proxyUrl: options.proxy, + torPort: options.torPort, + retry + }); + } + if (options.debug && typeof options.debug === "function") { + options.debug("request", { + url, + retry, + errorObject, + options + }); + } + try { + const resp = yield fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + redirect: options.redirect, + signal: options.signal, + agent: options.agent + }); + if (options.debug && typeof options.debug === "function") { + options.debug("response", resp); + } + if (!resp.ok) { + const errMsg = `Request to ${url} failed with error code ${resp.status}: +` + (yield resp.text()); + throw new Error(errMsg); + } + if (options.returnResponse) { + return resp; + } + const contentType = resp.headers.get("content-type"); + if (contentType == null ? void 0 : contentType.includes("application/json")) { + return yield resp.json(); + } + if (contentType == null ? void 0 : contentType.includes("text")) { + return yield resp.text(); + } + return resp; + } catch (error) { + if (timeout) { + clearTimeout(timeout); + } + errorObject = error; + retry++; + yield sleep(RETRY_ON); + } finally { + if (timeout) { + clearTimeout(timeout); + } + } + } + if (options.debug && typeof options.debug === "function") { + options.debug("error", errorObject); + } + throw errorObject; + }); +} +const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$d(void 0, null, function* () { + let signal; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { + controller.abort(); + }); + } + const init = __spreadProps$4(__spreadValues$5({}, options), { + method: req.method || "POST", + headers: req.headers, + body: req.body || void 0, + signal, + returnResponse: true + }); + const resp = yield fetchData(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = yield resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; +}); +const oracleMapper = /* @__PURE__ */ new Map(); +const multicallMapper = /* @__PURE__ */ new Map(); +function getGasOraclePlugin(networkKey, fetchOptions) { + const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; + return new ethers.FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async$d(this, null, function* () { + if (!oracleMapper.has(networkKey)) { + oracleMapper.set(networkKey, GasPriceOracle__factory.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); + } + if (!multicallMapper.has(networkKey)) { + multicallMapper.set( + networkKey, + Multicall__factory.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) + ); + } + const Oracle = oracleMapper.get(networkKey); + const Multicall2 = multicallMapper.get(networkKey); + const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield multicall(Multicall2, [ + { + contract: Oracle, + name: "timestamp" + }, + { + contract: Oracle, + name: "heartbeat" + }, + { + contract: Oracle, + name: "maxFeePerGas" + }, + { + contract: Oracle, + name: "maxPriorityFeePerGas" + } + ]); + const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); + if (!isOutdated) { + const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); + const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; + return { + gasPrice: maxFeePerGas, + maxFeePerGas, + maxPriorityFeePerGas + }; + } + const fetchReq = new ethers.FetchRequest(gasStationApi); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + if (isNode) { + fetchReq.setHeader("User-Agent", "ethers"); + } + const [ + { + bodyJson: { fast } + }, + { gasPrice } + ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); + return { + gasPrice, + maxFeePerGas: ethers.parseUnits(`${fast.maxFee}`, 9), + maxPriorityFeePerGas: ethers.parseUnits(`${fast.maxPriorityFee}`, 9) + }; + })); +} +function getProvider(rpcUrl, fetchOptions) { + return __async$d(this, null, function* () { + const fetchReq = new ethers.FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const _staticNetwork = yield new ethers.JsonRpcProvider(fetchReq).getNetwork(); + const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); + const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); + const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + const staticNetwork = new ethers.Network(_staticNetwork.name, _staticNetwork.chainId); + if (ensPlugin) { + staticNetwork.attachPlugin(ensPlugin); + } + if (gasCostPlugin) { + staticNetwork.attachPlugin(gasCostPlugin); + } + if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { + staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); + } else if (gasStationPlugin) { + staticNetwork.attachPlugin(gasStationPlugin); + } + const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; + return provider; + }); +} +function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { + const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; + const hasEns = Boolean(reverseRecordsContract); + const fetchReq = new ethers.FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = new ethers.Network(networkName, netId); + if (hasEns) { + staticNetwork.attachPlugin(new ethers.EnsPlugin(null, Number(netId))); + } + staticNetwork.attachPlugin(new ethers.GasCostPlugin()); + if (gasPriceOracleContract) { + staticNetwork.attachPlugin( + getGasOraclePlugin(`${netId}_${rpcUrl}`, { + gasPriceOracle: gasPriceOracleContract, + gasStationApi + }) + ); + } + const provider = new ethers.JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; + return provider; +} +const populateTransaction = (signer, tx) => __async$d(void 0, null, function* () { + const provider = signer.provider; + if (!tx.from) { + tx.from = signer.address; + } else if (tx.from !== signer.address) { + const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; + throw new Error(errMsg); + } + const [feeData, nonce] = yield Promise.all([ + (() => __async$d(void 0, null, function* () { + if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + return new ethers.FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); + } + if (tx.gasPrice) { + return new ethers.FeeData(BigInt(tx.gasPrice), null, null); + } + const fetchedFeeData = yield provider.getFeeData(); + if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { + return new ethers.FeeData( + null, + fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + fetchedFeeData.maxPriorityFeePerGas + ); + } else { + return new ethers.FeeData( + fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + null, + null + ); + } + }))(), + (() => __async$d(void 0, null, function* () { + if (tx.nonce) { + return tx.nonce; + } + let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); + if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { + console.log( + `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` + ); + fetchedNonce++; + } + return fetchedNonce; + }))() + ]); + tx.nonce = nonce; + if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { + tx.maxFeePerGas = feeData.maxFeePerGas; + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + if (!tx.type) { + tx.type = 2; + } + delete tx.gasPrice; + } else if (feeData.gasPrice) { + tx.gasPrice = feeData.gasPrice; + if (!tx.type) { + tx.type = 0; + } + delete tx.maxFeePerGas; + delete tx.maxPriorityFeePerGas; + } + tx.gasLimit = tx.gasLimit || (yield (() => __async$d(void 0, null, function* () { + try { + const gasLimit = yield provider.estimateGas(tx); + return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); + } catch (err) { + if (signer.gasFailover) { + console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + return BigInt("3000000"); + } + throw err; + } + }))()); + return tx; +}); +class TornadoWallet extends ethers.Wallet { + constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(key, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + static fromMnemonic(mneomnic, provider, index = 0, options) { + const defaultPath = `m/44'/60'/0'/0/${index}`; + const { privateKey } = ethers.HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); + return new TornadoWallet(privateKey, provider, options); + } + populateTransaction(tx) { + return __async$d(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoVoidSigner extends ethers.VoidSigner { + constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(address, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + populateTransaction(tx) { + return __async$d(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoRpcSigner extends ethers.JsonRpcSigner { + constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(provider, address); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + sendUncheckedTransaction(tx) { + return __async$d(this, null, function* () { + return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); + }); + } +} +class TornadoBrowserProvider extends ethers.BrowserProvider { + constructor(ethereum, network, options) { + super(ethereum, network); + this.options = options; + } + getSigner(address) { + return __async$d(this, null, function* () { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; + if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { + yield this.options.connectWallet(); + } + if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { + (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); + } + if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { + (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); + } + if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { + (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); + } + return new TornadoRpcSigner(this, signerAddress, this.options); + }); + } +} + +const GET_STATISTIC = ` + query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { + deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { + index + timestamp + blockNumber + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const _META = ` + query getMeta { + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_REGISTERED = ` + query getRegistered($first: Int, $fromBlock: Int) { + relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { + blockRegistration_gte: $fromBlock + }) { + id + address + ensName + blockRegistration + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_DEPOSITS = ` + query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { + deposits(first: $first, orderBy: index, orderDirection: asc, where: { + amount: $amount, + currency: $currency, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + commitment + index + timestamp + from + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_WITHDRAWALS = ` + query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { + withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { + currency: $currency, + amount: $amount, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + nullifier + to + fee + timestamp + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_NOTE_ACCOUNTS = ` + query getNoteAccount($address: String!) { + noteAccounts(where: { address: $address }) { + id + index + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ECHO_EVENTS = ` + query getNoteAccounts($first: Int, $fromBlock: Int) { + noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + id + blockNumber + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ENCRYPTED_NOTES = ` + query getEncryptedNotes($first: Int, $fromBlock: Int) { + encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + index + transactionHash + encryptedNote + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_EVENTS = ` + query getGovernanceEvents($first: Int, $fromBlock: Int) { + proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + proposer + target + startTime + endTime + description + } + votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + voter + support + votes + from + input + } + delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateTo + } + undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateFrom + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_APY = ` + stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { + id + date + dailyAmountBurned + } +`; + +var __defProp$4 = Object.defineProperty; +var __defProps$3 = Object.defineProperties; +var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; +var __hasOwnProp$4 = Object.prototype.hasOwnProperty; +var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$4 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + if (__getOwnPropSymbols$4) + for (var prop of __getOwnPropSymbols$4(b)) { + if (__propIsEnum$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); +var __async$c = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; +const first = 1e3; +function queryGraph(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + query, + variables, + fetchDataOptions: fetchDataOptions2 + }) { + var _a; + const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; + const { data, errors } = yield fetchData(graphUrl, __spreadProps$3(__spreadValues$4({}, fetchDataOptions2), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + query, + variables + }) + })); + if (errors) { + throw new Error(JSON.stringify(errors)); + } + if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { + throw new Error("Subgraph has indexing errors"); + } + return data; + }); +} +function getStatistic(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + deposits, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_STATISTIC, + variables: { + currency, + first: 10, + orderBy: "index", + orderDirection: "desc", + amount + }, + fetchDataOptions: fetchDataOptions2 + }); + const events = deposits.map((e) => ({ + timestamp: Number(e.timestamp), + leafIndex: Number(e.index), + blockNumber: Number(e.blockNumber) + })).reverse(); + const [lastEvent] = events.slice(-1); + return { + events, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getStatistic query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getMeta(_0) { + return __async$c(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { + try { + const { + _meta: { + block: { number: lastSyncBlock }, + hasIndexingErrors + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: _META, + fetchDataOptions: fetchDataOptions2 + }); + return { + lastSyncBlock, + hasIndexingErrors + }; + } catch (err) { + console.log("Error from getMeta query"); + console.log(err); + return { + lastSyncBlock: null, + hasIndexingErrors: null + }; + } + }); +} +function getRegisters({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_REGISTERED, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllRegisters(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + relayers: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Registers", + fromBlock: Number(firstEvent.blockRegistration), + toBlock: Number(lastEvent.blockRegistration), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); + fromBlock = Number(lastEvent.blockRegistration); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, address, ensName, blockRegistration }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockRegistration), + logIndex: Number(logIndex), + transactionHash, + ensName, + relayerAddress: ethers.getAddress(address) + }; + }); + return { + events: result, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllRegisters query"); + console.log(err); + return { events: [], lastSyncBlock: fromBlock }; + } + }); +} +function getDeposits({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_DEPOSITS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllDeposits(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + deposits: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Deposits", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + commitment, + leafIndex: Number(index), + timestamp: Number(timestamp), + from: ethers.getAddress(from) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllDeposits query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getWithdrawals({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_WITHDRAWALS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllWithdrawals(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + withdrawals: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Withdrawals", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + nullifierHash: nullifier, + to: ethers.getAddress(to), + fee, + timestamp: Number(timestamp) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllWithdrawals query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getNoteAccounts(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + address, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + noteAccounts: events, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_NOTE_ACCOUNTS, + variables: { + address: address.toLowerCase() + }, + fetchDataOptions: fetchDataOptions2 + }); + return { + events, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getNoteAccounts query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getGraphEchoEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ECHO_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGraphEchoEvents(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + noteAccounts: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EchoEvents", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => { + const [transactionHash, logIndex] = e.id.split("-"); + return { + blockNumber: Number(e.blockNumber), + logIndex: Number(logIndex), + transactionHash, + address: ethers.getAddress(e.address), + encryptedAccount: e.encryptedAccount + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGraphEchoEvents query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getEncryptedNotes({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ENCRYPTED_NOTES, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllEncryptedNotes(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + encryptedNotes: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EncryptedNotes", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => ({ + blockNumber: Number(e.blockNumber), + logIndex: Number(e.index), + transactionHash: e.transactionHash, + encryptedNote: e.encryptedNote + })); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllEncryptedNotes query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getGovernanceEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_GOVERNANCE_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGovernanceEvents(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const result = []; + let lastSyncBlock = fromBlock; + while (true) { + const { + proposals, + votes, + delegates, + undelegates, + _meta: { + block: { number: currentBlock } + } + } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; + if (eventsLength === 0) { + break; + } + const formattedProposals = proposals.map( + ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "ProposalCreated", + id: Number(proposalId), + proposer: ethers.getAddress(proposer), + target: ethers.getAddress(target), + startTime: Number(startTime), + endTime: Number(endTime), + description + }; + } + ); + const formattedVotes = votes.map( + ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { + if (!input || input.length > 2048) { + input = ""; + } + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Voted", + proposalId: Number(proposalId), + voter: ethers.getAddress(voter), + support, + votes: votes2, + from: ethers.getAddress(from), + input + }; + } + ); + const formattedDelegates = delegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Delegated", + account: ethers.getAddress(account), + delegateTo: ethers.getAddress(delegateTo) + }; + } + ); + const formattedUndelegates = undelegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Undelegated", + account: ethers.getAddress(account), + delegateFrom: ethers.getAddress(delegateFrom) + }; + } + ); + let formattedEvents = [ + ...formattedProposals, + ...formattedVotes, + ...formattedDelegates, + ...formattedUndelegates + ].sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }); + if (eventsLength < 900) { + result.push(...formattedEvents); + break; + } + const [firstEvent] = formattedEvents; + const [lastEvent2] = formattedEvents.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Governance Events", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: eventsLength + }); + } + formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + result.push(...formattedEvents); + } + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGovernance query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} + +var graph = /*#__PURE__*/Object.freeze({ + __proto__: null, + GET_DEPOSITS: GET_DEPOSITS, + GET_ECHO_EVENTS: GET_ECHO_EVENTS, + GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, + GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, + GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, + GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, + GET_REGISTERED: GET_REGISTERED, + GET_STATISTIC: GET_STATISTIC, + GET_WITHDRAWALS: GET_WITHDRAWALS, + _META: _META, + getAllDeposits: getAllDeposits, + getAllEncryptedNotes: getAllEncryptedNotes, + getAllGovernanceEvents: getAllGovernanceEvents, + getAllGraphEchoEvents: getAllGraphEchoEvents, + getAllRegisters: getAllRegisters, + getAllWithdrawals: getAllWithdrawals, + getDeposits: getDeposits, + getEncryptedNotes: getEncryptedNotes, + getGovernanceEvents: getGovernanceEvents, + getGraphEchoEvents: getGraphEchoEvents, + getMeta: getMeta, + getNoteAccounts: getNoteAccounts, + getRegisters: getRegisters, + getStatistic: getStatistic, + getWithdrawals: getWithdrawals, + queryGraph: queryGraph +}); + +var __async$b = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class BatchBlockService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getBlock(blockTag) { + return __async$b(this, null, function* () { + const blockObject = yield this.provider.getBlock(blockTag); + if (!blockObject) { + const errMsg = `No block for ${blockTag}`; + throw new Error(errMsg); + } + return blockObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((blocks, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return (() => __async$b(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(blocks.map((b) => this.getBlock(b))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchBlocks(blocks) { + return __async$b(this, null, function* () { + let blockCount = 0; + const results = []; + for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + blockCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: blockCount / blocks.length, + currentIndex: blockCount, + totalIndex: blocks.length + }); + } + } + return results; + }); + } +} +class BatchTransactionService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getTransaction(txHash) { + return __async$b(this, null, function* () { + const txObject = yield this.provider.getTransaction(txHash); + if (!txObject) { + const errMsg = `No transaction for ${txHash}`; + throw new Error(errMsg); + } + return txObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((txs, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return (() => __async$b(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchTransactions(txs) { + return __async$b(this, null, function* () { + let txCount = 0; + const results = []; + for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + txCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); + } + } + return results; + }); + } +} +class BatchEventsService { + constructor({ + provider, + contract, + onProgress, + concurrencySize = 10, + blocksPerRequest = 2e3, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.contract = contract; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.blocksPerRequest = blocksPerRequest; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getPastEvents(_0) { + return __async$b(this, arguments, function* ({ fromBlock, toBlock, type }) { + let err; + let retries = 0; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield this.contract.queryFilter(type, fromBlock, toBlock); + } catch (e) { + err = e; + retries++; + if (e.message.includes("after last accepted block")) { + const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); + toBlock = acceptedBlock; + } + yield sleep(this.retryOn); + } + } + throw err; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((event, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return this.getPastEvents(event); + })); + } + getBatchEvents(_0) { + return __async$b(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + const eventsToSync = []; + for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { + const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; + eventsToSync.push({ fromBlock: i, toBlock: j, type }); + } + const events = []; + const eventChunk = chunk(eventsToSync, this.concurrencySize); + let chunkCount = 0; + for (const chunk2 of eventChunk) { + chunkCount++; + const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); + events.push(...fetchedEvents); + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: chunkCount / eventChunk.length, + type, + fromBlock: chunk2[0].fromBlock, + toBlock: chunk2[chunk2.length - 1].toBlock, + count: fetchedEvents.length + }); + } + } + return events; + }); + } +} + +var __defProp$3 = Object.defineProperty; +var __defProps$2 = Object.defineProperties; +var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp$3 = Object.prototype.hasOwnProperty; +var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$3 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + if (__getOwnPropSymbols$3) + for (var prop of __getOwnPropSymbols$3(b)) { + if (__propIsEnum$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async$a = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const DEPOSIT = "deposit"; +const WITHDRAWAL = "withdrawal"; +class BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + contract, + type = "", + deployedBlock = 0, + fetchDataOptions: fetchDataOptions2 + }) { + this.netId = netId; + this.provider = provider; + this.graphApi = graphApi; + this.subgraphName = subgraphName; + this.fetchDataOptions = fetchDataOptions2; + this.contract = contract; + this.type = type; + this.deployedBlock = deployedBlock; + this.batchEventsService = new BatchEventsService({ + provider, + contract, + onProgress: this.updateEventProgress + }); + } + getInstanceName() { + return ""; + } + getType() { + return this.type || ""; + } + getGraphMethod() { + return ""; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { + } + updateBlockProgress({ percentage, currentIndex, totalIndex }) { + } + updateTransactionProgress({ percentage, currentIndex, totalIndex }) { + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + formatEvents(events) { + return __async$a(this, null, function* () { + return yield new Promise((resolve) => resolve(events)); + }); + } + /** + * Get saved or cached events + */ + getEventsFromDB() { + return __async$a(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getEventsFromCache() { + return __async$a(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getSavedEvents() { + return __async$a(this, null, function* () { + let cachedEvents = yield this.getEventsFromDB(); + if (!cachedEvents || !cachedEvents.events.length) { + cachedEvents = yield this.getEventsFromCache(); + } + return cachedEvents; + }); + } + /** + * Get latest events + */ + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ + fromBlock, + methodName = "" + }) { + if (!this.graphApi || !this.subgraphName) { + return { + events: [], + lastBlock: fromBlock + }; + } + const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$3({ + fromBlock + }, this.getGraphParams())); + return { + events, + lastBlock: lastSyncBlock + }; + }); + } + getEventsFromRpc(_0) { + return __async$a(this, arguments, function* ({ + fromBlock, + toBlock + }) { + try { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + if (fromBlock >= toBlock) { + return { + events: [], + lastBlock: toBlock + }; + } + this.updateEventProgress({ percentage: 0, type: this.getType() }); + const events = yield this.formatEvents( + yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) + ); + if (!events.length) { + return { + events, + lastBlock: toBlock + }; + } + return { + events, + lastBlock: toBlock + }; + } catch (err) { + console.log(err); + return { + events: [], + lastBlock: fromBlock + }; + } + }); + } + getLatestEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + const allEvents = []; + const graphEvents = yield this.getEventsFromGraph({ fromBlock }); + const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; + const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); + allEvents.push(...graphEvents.events); + allEvents.push(...rpcEvents.events); + const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; + return { + events: allEvents, + lastBlock + }; + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validateEvents({ events, lastBlock }) { + } + /** + * Handle saving events + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + saveEvents(_0) { + return __async$a(this, arguments, function* ({ events, lastBlock }) { + }); + } + /** + * Trigger saving and receiving latest events + */ + updateEvents() { + return __async$a(this, null, function* () { + const savedEvents = yield this.getSavedEvents(); + let fromBlock = this.deployedBlock; + if (savedEvents && savedEvents.lastBlock) { + fromBlock = savedEvents.lastBlock + 1; + } + const newEvents = yield this.getLatestEvents({ fromBlock }); + const eventSet = /* @__PURE__ */ new Set(); + let allEvents = []; + allEvents.push(...savedEvents.events); + allEvents.push(...newEvents.events); + allEvents = allEvents.sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }).filter(({ transactionHash, logIndex }) => { + const eventKey = `${transactionHash}_${logIndex}`; + const hasEvent = eventSet.has(eventKey); + eventSet.add(eventKey); + return !hasEvent; + }); + const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; + this.validateEvents({ events: allEvents, lastBlock }); + yield this.saveEvents({ events: allEvents, lastBlock }); + return { + events: allEvents, + lastBlock + }; + }); + } +} +class BaseDepositsService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.amount = amount; + this.currency = currency; + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + this.batchBlockService = new BatchBlockService({ + provider, + onProgress: this.updateBlockProgress + }); + } + getInstanceName() { + return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; + } + getGraphMethod() { + return `getAll${this.getType()}s`; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + amount: this.amount, + currency: this.currency, + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + formatEvents(events) { + return __async$a(this, null, function* () { + const type = this.getType().toLowerCase(); + if (type === DEPOSIT) { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { commitment, leafIndex, timestamp } = args; + return { + blockNumber, + logIndex, + transactionHash, + commitment, + leafIndex: Number(leafIndex), + timestamp: Number(timestamp) + }; + }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) + ]); + return formattedEvents.map((event) => { + const { from } = txs.find(({ hash }) => hash === event.transactionHash); + return __spreadProps$2(__spreadValues$3({}, event), { + from + }); + }); + } else { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { nullifierHash, to, fee } = args; + return { + blockNumber, + logIndex, + transactionHash, + nullifierHash: String(nullifierHash), + to: ethers.getAddress(to), + fee: String(fee) + }; + }); + const blocks = yield this.batchBlockService.getBatchBlocks([ + ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) + ]); + return formattedEvents.map((event) => { + const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); + return __spreadProps$2(__spreadValues$3({}, event), { + timestamp + }); + }); + } + }); + } + validateEvents({ events }) { + if (events.length && this.getType().toLowerCase() === DEPOSIT) { + const lastEvent = events[events.length - 1]; + if (lastEvent.leafIndex !== events.length - 1) { + const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; + throw new Error(errMsg); + } + } + } +} +class BaseEchoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `echo_${this.netId}`; + } + getType() { + return "Echo"; + } + getGraphMethod() { + return "getAllGraphEchoEvents"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { who, data } = args; + if (who && data) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + address: who, + encryptedAccount: data + }); + } + }).filter((e) => e); + }); + } + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseEncryptedNotesService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `encrypted_notes_${this.netId}`; + } + getType() { + return "EncryptedNote"; + } + getGraphMethod() { + return "getAllEncryptedNotes"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { encryptedNote } = args; + if (encryptedNote) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + encryptedNote + }); + } + }).filter((e) => e); + }); + } +} +class BaseGovernanceService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + } + getInstanceName() { + return `governance_${this.netId}`; + } + getType() { + return "*"; + } + getGraphMethod() { + return "getAllGovernanceEvents"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + const proposalEvents = []; + const votedEvents = []; + const delegatedEvents = []; + const undelegatedEvents = []; + events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash, + event + }; + if (event === "ProposalCreated") { + const { id, proposer, target, startTime, endTime, description } = args; + proposalEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + id: Number(id), + proposer, + target, + startTime: Number(startTime), + endTime: Number(endTime), + description + })); + } + if (event === "Voted") { + const { proposalId, voter, support, votes } = args; + votedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + proposalId: Number(proposalId), + voter, + support, + votes, + from: "", + input: "" + })); + } + if (event === "Delegated") { + const { account, to: delegateTo } = args; + delegatedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + account, + delegateTo + })); + } + if (event === "Undelegated") { + const { account, from: delegateFrom } = args; + undelegatedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + account, + delegateFrom + })); + } + }); + if (votedEvents.length) { + this.updateTransactionProgress({ percentage: 0 }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) + ]); + votedEvents.forEach((event, index) => { + let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); + if (!input || input.length > 2048) { + input = ""; + } + votedEvents[index].from = from; + votedEvents[index].input = input; + }); + } + return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; + }); + } + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseRegistryService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `registered_${this.netId}`; + } + // Name of type used for events + getType() { + return "RelayerRegistered"; + } + // Name of method used for graph + getGraphMethod() { + return "getAllRegisters"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + ensName: args.ensName, + relayerAddress: args.relayerAddress + }); + }); + }); + } + fetchRelayers() { + return __async$a(this, null, function* () { + return (yield this.updateEvents()).events; + }); + } +} + +var __async$9 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function existsAsync(fileOrDir) { + return __async$9(this, null, function* () { + try { + yield promises.stat(fileOrDir); + return true; + } catch (e) { + return false; + } + }); +} +function zipAsync(file) { + return new Promise((res, rej) => { + fflate.zip(file, { mtime: /* @__PURE__ */ new Date("1/1/1980") }, (err, data) => { + if (err) { + rej(err); + return; + } + res(data); + }); + }); +} +function unzipAsync(data) { + return new Promise((res, rej) => { + fflate.unzip(data, {}, (err, data2) => { + if (err) { + rej(err); + return; + } + res(data2); + }); + }); +} +function saveUserFile(_0) { + return __async$9(this, arguments, function* ({ + fileName, + userDirectory, + dataString + }) { + fileName = fileName.toLowerCase(); + const filePath = path.join(userDirectory, fileName); + const payload = yield zipAsync({ + [fileName]: new TextEncoder().encode(dataString) + }); + if (!(yield existsAsync(userDirectory))) { + yield promises.mkdir(userDirectory, { recursive: true }); + } + yield promises.writeFile(filePath + ".zip", payload); + yield promises.writeFile(filePath, dataString); + }); +} +function loadSavedEvents(_0) { + return __async$9(this, arguments, function* ({ + name, + userDirectory, + deployedBlock + }) { + const filePath = path.join(userDirectory, `${name}.json`.toLowerCase()); + if (!(yield existsAsync(filePath))) { + return { + events: [], + lastBlock: null + }; + } + try { + const events = JSON.parse(yield promises.readFile(filePath, { encoding: "utf8" })); + return { + events, + lastBlock: events && events.length ? events[events.length - 1].blockNumber : deployedBlock + }; + } catch (err) { + console.log("Method loadSavedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} +function download(_0) { + return __async$9(this, arguments, function* ({ name, cacheDirectory }) { + const fileName = `${name}.json`.toLowerCase(); + const zipName = `${fileName}.zip`; + const zipPath = path.join(cacheDirectory, zipName); + const data = yield promises.readFile(zipPath); + const { [fileName]: content } = yield unzipAsync(data); + return new TextDecoder().decode(content); + }); +} +function loadCachedEvents(_0) { + return __async$9(this, arguments, function* ({ + name, + cacheDirectory, + deployedBlock + }) { + try { + const module = yield download({ cacheDirectory, name }); + if (module) { + const events = JSON.parse(module); + const lastBlock = events && events.length ? events[events.length - 1].blockNumber : deployedBlock; + return { + events, + lastBlock + }; + } + return { + events: [], + lastBlock: deployedBlock + }; + } catch (err) { + console.log("Method loadCachedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} + +var __async$8 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class NodeDepositsService extends BaseDepositsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} deposit txs of ${totalIndex}`); + } + } + updateBlockProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} withdrawal blocks of ${totalIndex}`); + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log( + "Updating events for", + this.amount, + this.currency.toUpperCase(), + `${this.getType().toLowerCase()}s +` + ); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log("Updating events for", this.amount, this.currency.toUpperCase(), `${this.getType().toLowerCase()}s +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: `${this.getType()}s`, hAlign: "center" }], + ["Instance", `${this.netId} chain ${this.amount} ${this.currency.toUpperCase()}`], + ["Anonymity set", `${events.length} equal user ${this.getType().toLowerCase()}s`], + [{ colSpan: 2, content: `Latest ${this.getType().toLowerCase()}s` }], + ...events.slice(events.length - 10).reverse().map(({ timestamp }, index) => { + const eventIndex = events.length - index; + const eventTime = moment.unix(timestamp).fromNow(); + return [eventIndex, eventTime]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEchoService extends BaseEchoService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Echo Accounts", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEncryptedNotesService extends BaseEncryptedNotesService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Encrypted Notes", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeGovernanceService extends BaseGovernanceService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} governance txs of ${totalIndex}`); + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Governance Events", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeRegistryService extends BaseRegistryService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Registered Relayers", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} + +var __defProp$2 = Object.defineProperty; +var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; +var __hasOwnProp$2 = Object.prototype.hasOwnProperty; +var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$2 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + if (__getOwnPropSymbols$2) + for (var prop of __getOwnPropSymbols$2(b)) { + if (__propIsEnum$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + } + return a; +}; +var NetId = /* @__PURE__ */ ((NetId2) => { + NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; + NetId2[NetId2["BSC"] = 56] = "BSC"; + NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; + NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; + NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; + NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; + NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; + NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + return NetId2; +})(NetId || {}); +const theGraph = { + name: "Hosted Graph", + url: "https://api.thegraph.com" +}; +const tornado = { + name: "Tornado Subgraphs", + url: "https://tornadocash-rpc.com" +}; +const defaultConfig = { + [1 /* MAINNET */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 80, + fast: 50, + standard: 25, + low: 8 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Mainnet", + deployedBlock: 9116966, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + mevblockerRPC: { + name: "MevblockerRPC", + url: "https://rpc.mevblocker.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/ethereum-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://eth-mainnet.nodereal.io/v1/1659dfb40aa24bbb8153a677b98064d7" + }, + notadegenRPC: { + name: "NotADegen RPC", + url: "https://rpc.notadegen.com/eth" + }, + keydonixRPC: { + name: "Keydonix RPC", + url: "https://ethereum.keydonix.com/v1/mainnet" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/eth" + } + }, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", + echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", + governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", + stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", + registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", + aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", + reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", + tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", + registrySubgraph: "tornadocash/tornado-relayer-registry", + governanceSubgraph: "tornadocash/tornado-governance", + subgraphs: { + tornado, + theGraph + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", + "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", + "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", + "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", + "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", + "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", + "100000": "0x23773E65ed146A459791799d01336DB287f25334" + }, + tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + }, + cdai: { + instanceAddress: { + "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", + "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", + "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", + "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" + }, + tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", + tokenGasLimit: 2e5, + symbol: "cDAI", + decimals: 8, + gasLimit: 7e5 + }, + usdc: { + instanceAddress: { + "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", + "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" + }, + tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + tokenGasLimit: 7e4, + symbol: "USDC", + decimals: 6, + gasLimit: 7e5 + }, + usdt: { + instanceAddress: { + "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", + "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" + }, + tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + tokenGasLimit: 7e4, + symbol: "USDT", + decimals: 6, + gasLimit: 7e5 + }, + wbtc: { + instanceAddress: { + "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", + "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", + "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" + }, + tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", + tokenGasLimit: 7e4, + symbol: "WBTC", + decimals: 8, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "mainnet-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 11474695, + NOTE_ACCOUNT_BLOCK: 11842486, + ENCRYPTED_NOTES_BLOCK: 12143762, + REGISTRY_BLOCK: 14173129, + MINING_BLOCK_TIME: 15 + } + }, + [56 /* BSC */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 5, + fast: 5, + standard: 5, + low: 5 + }, + nativeCurrency: "bnb", + currencyName: "BNB", + explorerUrl: "https://bscscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Binance Smart Chain", + deployedBlock: 8158799, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/bsc" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://bsc-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/bsc-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/bnb" + } + }, + tokens: { + bnb: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "BNB", + decimals: 18 + } + }, + ensSubdomainKey: "bsc-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 8159269, + ENCRYPTED_NOTES_BLOCK: 8159269 + } + }, + [137 /* POLYGON */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 100, + fast: 75, + standard: 50, + low: 30 + }, + nativeCurrency: "matic", + currencyName: "MATIC", + explorerUrl: "https://polygonscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Polygon (Matic) Network", + deployedBlock: 16257962, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", + tornadoSubgraph: "tornadocash/matic-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + chainnodes: { + name: "Tornado RPC", + url: "https://polygon-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/polygon-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/matic" + } + }, + tokens: { + matic: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "MATIC", + decimals: 18 + } + }, + ensSubdomainKey: "polygon-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 16257996, + ENCRYPTED_NOTES_BLOCK: 16257996 + } + }, + [10 /* OPTIMISM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 1e-3, + fast: 1e-3, + standard: 1e-3, + low: 1e-3 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://optimistic.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Optimism", + deployedBlock: 2243689, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", + tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/op" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://optimism-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + optimism: { + name: "Optimism RPC", + url: "https://mainnet.optimism.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/optimism-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/op" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "optimism-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 2243694, + ENCRYPTED_NOTES_BLOCK: 2243694 + } + }, + [42161 /* ARBITRUM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 4, + fast: 3, + standard: 2.52, + low: 2.29 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://arbiscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Arbitrum One", + deployedBlock: 3430648, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/arbitrum" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://arbitrum-one.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + arbitrum: { + name: "Arbitrum RPC", + url: "https://arb1.arbitrum.io/rpc" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + oneRpc: { + name: "1rpc", + url: "https://1rpc.io/arb" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "arbitrum-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 3430605, + ENCRYPTED_NOTES_BLOCK: 3430605 + } + }, + [100 /* GNOSIS */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 6, + fast: 5, + standard: 4, + low: 1 + }, + nativeCurrency: "xdai", + currencyName: "xDAI", + explorerUrl: "https://gnosisscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Gnosis Chain", + deployedBlock: 17754561, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/gnosis" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://gnosis-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + gnosis: { + name: "Gnosis RPC", + url: "https://rpc.gnosischain.com" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + blockPi: { + name: "BlockPi", + url: "https://gnosis.blockpi.network/v1/rpc/public" + } + }, + tokens: { + xdai: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "xDAI", + decimals: 18 + } + }, + ensSubdomainKey: "gnosis-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 17754564, + ENCRYPTED_NOTES_BLOCK: 17754564 + } + }, + [43114 /* AVALANCHE */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 225, + fast: 35, + standard: 25, + low: 25 + }, + nativeCurrency: "avax", + currencyName: "AVAX", + explorerUrl: "https://snowtrace.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Avalanche Mainnet", + deployedBlock: 4429818, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", + subgraphs: { + theGraph + }, + rpcUrls: { + oneRPC: { + name: "OneRPC", + url: "https://1rpc.io/avax/c" + }, + avalancheRPC: { + name: "Avalanche RPC", + url: "https://api.avax.network/ext/bc/C/rpc" + }, + meowRPC: { + name: "Meow RPC", + url: "https://avax.meowrpc.com" + } + }, + tokens: { + avax: { + instanceAddress: { + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" + }, + symbol: "AVAX", + decimals: 18 + } + }, + ensSubdomainKey: "avalanche-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 4429813, + ENCRYPTED_NOTES_BLOCK: 4429813 + } + }, + [11155111 /* SEPOLIA */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 2, + fast: 2, + standard: 2, + low: 2 + }, + nativeCurrency: "eth", + currencyName: "SepoliaETH", + explorerUrl: "https://sepolia.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Sepolia", + deployedBlock: 5594395, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", + governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", + stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", + registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", + aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", + reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", + tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", + subgraphs: { + tornado + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/sepolia" + }, + sepolia: { + name: "Sepolia RPC", + url: "https://rpc.sepolia.org" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://sepolia.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", + "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", + "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", + "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", + "1000": "0x50a637770F5d161999420F7d70d888DE47207145", + "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", + "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" + }, + tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "sepolia-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 5594395, + NOTE_ACCOUNT_BLOCK: 5594395, + ENCRYPTED_NOTES_BLOCK: 5594395, + MINING_BLOCK_TIME: 15 + } + } +}; +const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); +exports.customConfig = {}; +function addNetwork(newConfig) { + enabledChains.push( + ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) + ); + exports.customConfig = __spreadValues$2(__spreadValues$2({}, exports.customConfig), newConfig); +} +function getNetworkConfig() { + const allConfig = __spreadValues$2(__spreadValues$2({}, defaultConfig), exports.customConfig); + return enabledChains.reduce((acc, curr) => { + acc[curr] = allConfig[curr]; + return acc; + }, {}); +} +function getConfig(netId) { + const allConfig = getNetworkConfig(); + const chainConfig = allConfig[netId]; + if (!chainConfig) { + const errMsg = `No config found for network ${netId}!`; + throw new Error(errMsg); + } + return chainConfig; +} +function getInstanceByAddress({ netId, address }) { + const { tokens } = getConfig(netId); + for (const [currency, { instanceAddress }] of Object.entries(tokens)) { + for (const [amount, instance] of Object.entries(instanceAddress)) { + if (instance === address) { + return { + amount, + currency + }; + } + } + } +} +function getSubdomains() { + const allConfig = getNetworkConfig(); + return enabledChains.map((chain) => allConfig[chain].ensSubdomainKey); +} + +const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; +const bnType = { type: "string", BN: true }; +const statusSchema = { + type: "object", + properties: { + rewardAccount: addressType, + gasPrices: { + type: "object", + properties: { + fast: { type: "number" }, + additionalProperties: { type: "number" } + }, + required: ["fast"] + }, + netId: { type: "integer" }, + tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, + latestBlock: { type: "number" }, + version: { type: "string" }, + health: { + type: "object", + properties: { + status: { const: "true" }, + error: { type: "string" } + }, + required: ["status"] + }, + currentQueue: { type: "number" } + }, + required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] +}; +function getStatusSchema(netId, config) { + const { tokens, optionalTokens = [], nativeCurrency } = config; + const schema = JSON.parse(JSON.stringify(statusSchema)); + const instances = Object.keys(tokens).reduce( + (acc, token) => { + const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; + const amounts = Object.keys(instanceAddress); + const instanceProperties = { + type: "object", + properties: { + instanceAddress: { + type: "object", + properties: amounts.reduce((acc2, cur) => { + acc2[cur] = addressType; + return acc2; + }, {}), + required: amounts.filter((amount) => !optionalInstances.includes(amount)) + }, + decimals: { enum: [decimals] } + }, + required: ["instanceAddress", "decimals"].concat( + tokenAddress ? ["tokenAddress"] : [], + symbol ? ["symbol"] : [] + ) + }; + if (tokenAddress) { + instanceProperties.properties.tokenAddress = addressType; + } + if (symbol) { + instanceProperties.properties.symbol = { enum: [symbol] }; + } + acc.properties[token] = instanceProperties; + if (!optionalTokens.includes(token)) { + acc.required.push(token); + } + return acc; + }, + { + type: "object", + properties: {}, + required: [] + } + ); + schema.properties.instances = instances; + if (netId === NetId.MAINNET) { + const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); + const ethPrices = { + type: "object", + properties: _tokens.reduce((acc, token) => { + acc[token] = bnType; + return acc; + }, {}) + // required: _tokens + }; + schema.properties.ethPrices = ethPrices; + } + return schema; +} + +const jobsSchema = { + type: "object", + properties: { + error: { type: "string" }, + id: { type: "string" }, + type: { type: "string" }, + status: { type: "string" }, + contract: { type: "string" }, + proof: { type: "string" }, + args: { + type: "array", + items: { type: "string" } + }, + txHash: { type: "string" }, + confirmations: { type: "number" }, + failedReason: { type: "string" } + }, + required: ["id", "status"] +}; + +const ajv = new Ajv({ allErrors: true }); +ajv.addKeyword({ + keyword: "BN", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validate: (schema, data) => { + try { + BigInt(data); + return true; + } catch (e) { + return false; + } + }, + errors: true +}); + +var __async$7 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class Pedersen { + constructor() { + this.pedersenPromise = this.initPedersen(); + } + initPedersen() { + return __async$7(this, null, function* () { + this.pedersenHash = yield circomlibjs.buildPedersenHash(); + this.babyJub = this.pedersenHash.babyJub; + }); + } + unpackPoint(buffer) { + return __async$7(this, null, function* () { + var _a, _b; + yield this.pedersenPromise; + return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); + }); + } + toStringBuffer(buffer) { + var _a; + return (_a = this.babyJub) == null ? void 0 : _a.F.toString(buffer); + } +} +const pedersen = new Pedersen(); +function buffPedersenHash(buffer) { + return __async$7(this, null, function* () { + const [hash] = yield pedersen.unpackPoint(buffer); + return pedersen.toStringBuffer(hash); + }); +} + +var __async$6 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function createDeposit(_0) { + return __async$6(this, arguments, function* ({ nullifier, secret }) { + const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]); + const noteHex = toFixedHex(bytesToBN(preimage), 62); + const commitment = BigInt(yield buffPedersenHash(preimage)); + const commitmentHex = toFixedHex(commitment); + const nullifierHash = BigInt(yield buffPedersenHash(leInt2Buff(nullifier))); + const nullifierHex = toFixedHex(nullifierHash); + return { + preimage, + noteHex, + commitment, + commitmentHex, + nullifierHash, + nullifierHex + }; + }); +} +class Deposit { + constructor({ + currency, + amount, + netId, + nullifier, + secret, + note, + noteHex, + invoice, + commitmentHex, + nullifierHex + }) { + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.nullifier = nullifier; + this.secret = secret; + this.note = note; + this.noteHex = noteHex; + this.invoice = invoice; + this.commitmentHex = commitmentHex; + this.nullifierHex = nullifierHex; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + nullifier: this.nullifier, + secret: this.secret, + note: this.note, + noteHex: this.noteHex, + invoice: this.invoice, + commitmentHex: this.commitmentHex, + nullifierHex: this.nullifierHex + }, + null, + 2 + ); + } + static createNote(_0) { + return __async$6(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { + if (!nullifier) { + nullifier = rBigInt(31); + } + if (!secret) { + secret = rBigInt(31); + } + const depositObject = yield createDeposit({ + nullifier, + secret + }); + const newDeposit = new Deposit({ + currency: currency.toLowerCase(), + amount, + netId, + note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`, + noteHex: depositObject.noteHex, + invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } + static parseNote(noteString) { + return __async$6(this, null, function* () { + const noteRegex = new RegExp("tornado-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{124})", "g"); + const match = noteRegex.exec(noteString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + const bytes = bnToBytes("0x" + matchGroup.note); + const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString()); + const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString()); + const depositObject = yield createDeposit({ nullifier, secret }); + const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`; + const newDeposit = new Deposit({ + currency, + amount, + netId, + note: noteString, + noteHex: depositObject.noteHex, + invoice, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } +} +class Invoice { + constructor(invoiceString) { + const invoiceRegex = new RegExp("tornadoInvoice-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{64})", "g"); + const match = invoiceRegex.exec(invoiceString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.commitment = "0x" + matchGroup.commitment; + this.invoice = invoiceString; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + commitment: this.commitment, + invoice: this.invoice + }, + null, + 2 + ); + } +} + +function packEncryptedMessage({ nonce, ephemPublicKey, ciphertext }) { + const nonceBuf = toFixedHex(bytesToHex(base64ToBytes(nonce)), 24); + const ephemPublicKeyBuf = toFixedHex(bytesToHex(base64ToBytes(ephemPublicKey)), 32); + const ciphertextBuf = bytesToHex(base64ToBytes(ciphertext)); + const messageBuff = concatBytes(hexToBytes(nonceBuf), hexToBytes(ephemPublicKeyBuf), hexToBytes(ciphertextBuf)); + return bytesToHex(messageBuff); +} +function unpackEncryptedMessage(encryptedMessage) { + const messageBuff = hexToBytes(encryptedMessage); + const nonceBuf = bytesToBase64(messageBuff.slice(0, 24)); + const ephemPublicKeyBuf = bytesToBase64(messageBuff.slice(24, 56)); + const ciphertextBuf = bytesToBase64(messageBuff.slice(56)); + return { + messageBuff: bytesToHex(messageBuff), + version: "x25519-xsalsa20-poly1305", + nonce: nonceBuf, + ephemPublicKey: ephemPublicKeyBuf, + ciphertext: ciphertextBuf + }; +} +class NoteAccount { + constructor({ netId, blockNumber, recoveryKey, Echoer: Echoer2 }) { + if (!recoveryKey) { + recoveryKey = bytesToHex(crypto.getRandomValues(new Uint8Array(32))).slice(2); + } + this.netId = Math.floor(Number(netId)); + this.blockNumber = blockNumber; + this.recoveryKey = recoveryKey; + this.recoveryAddress = ethers.computeAddress("0x" + recoveryKey); + this.recoveryPublicKey = ethSigUtil.getEncryptionPublicKey(recoveryKey); + this.Echoer = Echoer2; + } + /** + * Intends to mock eth_getEncryptionPublicKey behavior from MetaMask + * In order to make the recoveryKey retrival from Echoer possible from the bare private key + */ + static getWalletPublicKey(wallet) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + return ethSigUtil.getEncryptionPublicKey(privateKey); + } + // This function intends to provide an encrypted value of recoveryKey for an on-chain Echoer backup purpose + // Thus, the pubKey should be derived by a Wallet instance or from Web3 wallets + // pubKey: base64 encoded 32 bytes key from https://docs.metamask.io/wallet/reference/eth_getencryptionpublickey/ + getEncryptedAccount(walletPublicKey) { + const encryptedData = ethSigUtil.encrypt({ + publicKey: walletPublicKey, + data: this.recoveryKey, + version: "x25519-xsalsa20-poly1305" + }); + const data = packEncryptedMessage(encryptedData); + return { + // Use this later to save hexPrivateKey generated with + // Buffer.from(JSON.stringify(encryptedData)).toString('hex') + // As we don't use buffer with this library we should leave UI to do the rest + encryptedData, + // Data that could be used as an echo(data) params + data + }; + } + /** + * Decrypt Echoer backuped note encryption account with private keys + */ + decryptAccountsWithWallet(wallet, events) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedAccount); + const recoveryKey = ethSigUtil.decrypt({ + encryptedData: unpackedMessage, + privateKey + }); + decryptedEvents.push( + new NoteAccount({ + netId: this.netId, + blockNumber: event.blockNumber, + recoveryKey, + Echoer: this.Echoer + }) + ); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + decryptNotes(events) { + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedNote); + const [address, noteHex] = ethSigUtil.decrypt({ + encryptedData: unpackedMessage, + privateKey: this.recoveryKey + }).split("-"); + decryptedEvents.push({ + blockNumber: event.blockNumber, + address: ethers.getAddress(address), + noteHex + }); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + encryptNote({ address, noteHex }) { + const encryptedData = ethSigUtil.encrypt({ + publicKey: this.recoveryPublicKey, + data: `${address}-${noteHex}`, + version: "x25519-xsalsa20-poly1305" + }); + return packEncryptedMessage(encryptedData); + } +} + +const DUMMY_ADDRESS = "0x1111111111111111111111111111111111111111"; +const DUMMY_NONCE = "0x1111111111111111111111111111111111111111111111111111111111111111"; +const DUMMY_WITHDRAW_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; +function convertETHToTokenAmount(amountInWei, tokenPriceInWei, tokenDecimals = 18) { + const tokenDecimalsMultiplier = BigInt(10 ** Number(tokenDecimals)); + return BigInt(amountInWei) * tokenDecimalsMultiplier / BigInt(tokenPriceInWei); +} +class TornadoFeeOracle { + constructor(ovmGasPriceOracle) { + if (ovmGasPriceOracle) { + this.ovmGasPriceOracle = ovmGasPriceOracle; + } + } + /** + * Calculate L1 fee for op-stack chains + * + * This is required since relayers would pay the full transaction fees for users + */ + fetchL1OptimismFee(tx) { + if (!this.ovmGasPriceOracle) { + return new Promise((resolve) => resolve(BigInt(0))); + } + if (!tx) { + tx = { + type: 0, + gasLimit: 1e6, + nonce: Number(DUMMY_NONCE), + data: DUMMY_WITHDRAW_DATA, + gasPrice: ethers.parseUnits("1", "gwei"), + from: DUMMY_ADDRESS, + to: DUMMY_ADDRESS + }; + } + return this.ovmGasPriceOracle.getL1Fee.staticCall(ethers.Transaction.from(tx).unsignedSerialized); + } + /** + * We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal + * So we default with 1M gas which is enough for two or three swaps + * Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI + */ + defaultEthRefund(gasPrice, gasLimit) { + return (gasPrice ? BigInt(gasPrice) : ethers.parseUnits("30", "gwei")) * BigInt(gasLimit || 1e6); + } + /** + * Calculates token amount for required ethRefund purchases required to calculate fees + */ + calculateTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals) { + return convertETHToTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals); + } + /** + * Warning: For tokens you need to check if the fees are above denomination + * (Usually happens for small denomination pool or if the gas price is high) + */ + calculateRelayerFee({ + gasPrice, + gasLimit = 6e5, + l1Fee = 0, + denomination, + ethRefund = BigInt(0), + tokenPriceInWei, + tokenDecimals = 18, + relayerFeePercent = 0.33, + isEth = true, + premiumPercent = 20 + }) { + const gasCosts = BigInt(gasPrice) * BigInt(gasLimit) + BigInt(l1Fee); + const relayerFee = BigInt(denomination) * BigInt(Math.floor(1e4 * relayerFeePercent)) / BigInt(1e4 * 100); + if (isEth) { + return (gasCosts + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } + const feeInEth = gasCosts + BigInt(ethRefund); + return (convertETHToTokenAmount(feeInEth, tokenPriceInWei, tokenDecimals) + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } +} + +var __async$5 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class Mimc { + constructor() { + this.mimcPromise = this.initMimc(); + } + initMimc() { + return __async$5(this, null, function* () { + this.sponge = yield circomlibjs.buildMimcSponge(); + this.hash = (left, right) => { + var _a, _b; + return (_b = this.sponge) == null ? void 0 : _b.F.toString((_a = this.sponge) == null ? void 0 : _a.multiHash([BigInt(left), BigInt(right)])); + }; + }); + } + getHash() { + return __async$5(this, null, function* () { + yield this.mimcPromise; + return { + sponge: this.sponge, + hash: this.hash + }; + }); + } +} +const mimc = new Mimc(); + +var __async$4 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class MerkleTreeService { + constructor({ + netId, + amount, + currency, + Tornado, + commitmentHex, + merkleTreeHeight = 20, + emptyElement = "21663839004416932945382355908790599225266501822907911457504978515578255421292", + merkleWorkerPath + }) { + const instanceName = `${netId}_${currency}_${amount}`; + this.currency = currency; + this.amount = amount; + this.netId = Number(netId); + this.Tornado = Tornado; + this.instanceName = instanceName; + this.commitmentHex = commitmentHex; + this.merkleTreeHeight = merkleTreeHeight; + this.emptyElement = emptyElement; + this.merkleWorkerPath = merkleWorkerPath; + } + createTree(events) { + return __async$4(this, null, function* () { + const { hash: hashFunction } = yield mimc.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (isNode) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new worker_threads.Worker(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return fixedMerkleTree.MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + }); + }); + return fixedMerkleTree.MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new fixedMerkleTree.MerkleTree(this.merkleTreeHeight, events, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + createPartialTree(_0) { + return __async$4(this, arguments, function* ({ edge, elements }) { + const { hash: hashFunction } = yield mimc.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (isNode) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new worker_threads.Worker(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return fixedMerkleTree.PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + }); + }); + return fixedMerkleTree.PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new fixedMerkleTree.PartialMerkleTree(this.merkleTreeHeight, edge, elements, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + verifyTree(events) { + return __async$4(this, null, function* () { + console.log( + ` +Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while +` + ); + console.time("Created tree in"); + const tree = yield this.createTree(events.map(({ commitment }) => commitment)); + console.timeEnd("Created tree in"); + console.log(""); + const isKnownRoot = yield this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root))); + if (!isKnownRoot) { + const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; + throw new Error(errMsg); + } + return tree; + }); + } +} + +function parseNumber(value) { + if (!value || isNaN(Number(value))) { + throw new commander.InvalidArgumentError("Invalid Number"); + } + return Number(value); +} +function parseUrl(value) { + if (!value || !validateUrl(value, ["http:", "https:"])) { + throw new commander.InvalidArgumentError("Invalid URL"); + } + return value; +} +function parseRelayer(value) { + if (!value || !(value.endsWith(".eth") || validateUrl(value, ["http:", "https:"]))) { + throw new commander.InvalidArgumentError("Invalid Relayer ETH address or URL"); + } + return value; +} +function parseAddress(value) { + if (!value) { + throw new commander.InvalidArgumentError("Invalid Address"); + } + try { + return ethers.getAddress(value); + } catch (e) { + throw new commander.InvalidArgumentError("Invalid Address"); + } +} +function parseMnemonic(value) { + if (!value) { + throw new commander.InvalidArgumentError("Invalid Mnemonic"); + } + try { + ethers.Mnemonic.fromPhrase(value); + } catch (e) { + throw new commander.InvalidArgumentError("Invalid Mnemonic"); + } + return value; +} +function parseKey(value) { + if (!value) { + throw new commander.InvalidArgumentError("Invalid Private Key"); + } + if (value.length === 64) { + value = "0x" + value; + } + try { + ethers.computeAddress(value); + } catch (e) { + throw new commander.InvalidArgumentError("Invalid Private Key"); + } + return value; +} +function parseRecoveryKey(value) { + if (!value) { + throw new commander.InvalidArgumentError("Invalid Recovery Key"); + } + try { + ethers.computeAddress("0x" + value); + } catch (e) { + throw new commander.InvalidArgumentError("Invalid Recovery Key"); + } + return value; +} + +class TokenPriceOracle { + constructor(provider, multicall2, oracle) { + this.provider = provider; + this.multicall = multicall2; + this.oracle = oracle; + } + fetchPrices(tokens) { + if (!this.oracle) { + return new Promise((resolve) => resolve(tokens.map(() => ethers.parseEther("0.0001")))); + } + return multicall( + this.multicall, + tokens.map((token) => ({ + contract: this.oracle, + name: "getRateToEth", + params: [token, true] + })) + ); + } +} + +var __defProp$1 = Object.defineProperty; +var __defProps$1 = Object.defineProperties; +var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; +var __hasOwnProp$1 = Object.prototype.hasOwnProperty; +var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$1 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + if (__getOwnPropSymbols$1) + for (var prop of __getOwnPropSymbols$1(b)) { + if (__propIsEnum$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); +var __async$3 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const MIN_STAKE_BALANCE = ethers.parseEther("500"); +const semVerRegex = new RegExp("^(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)(?:-(?(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); +function parseSemanticVersion(version) { + const { groups } = semVerRegex.exec(version); + return groups; +} +function isRelayerUpdated(relayerVersion, netId) { + const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); + const requiredMajor = netId === NetId.MAINNET ? "4" : "5"; + const isUpdatedMajor = major === requiredMajor; + if (prerelease) + return false; + return isUpdatedMajor && (Number(patch) >= 5 || netId !== NetId.MAINNET); +} +function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { + if (tornadoServiceFee < minFee) { + tornadoServiceFee = minFee; + } else if (tornadoServiceFee >= maxFee) { + return BigInt(0); + } + const serviceFeeCoefficient = (tornadoServiceFee - minFee) ** 2; + const feeDiffCoefficient = 1 / (maxFee - minFee) ** 2; + const coefficientsMultiplier = 1 - feeDiffCoefficient * serviceFeeCoefficient; + return BigInt(Math.floor(Number(stakeBalance) * coefficientsMultiplier)); +} +function getWeightRandom(weightsScores, random) { + for (let i = 0; i < weightsScores.length; i++) { + if (random < weightsScores[i]) { + return i; + } + random = random - weightsScores[i]; + } + return Math.floor(Math.random() * weightsScores.length); +} +function getSupportedInstances(instanceList) { + const rawList = Object.values(instanceList).map(({ instanceAddress }) => { + return Object.values(instanceAddress); + }).flat(); + return rawList.map((l) => ethers.getAddress(l)); +} +function pickWeightedRandomRelayer(relayers, netId) { + let minFee, maxFee; + if (netId !== NetId.MAINNET) { + minFee = 0.01; + maxFee = 0.3; + } + const weightsScores = relayers.map((el) => calculateScore(el, minFee, maxFee)); + const totalWeight = weightsScores.reduce((acc, curr) => { + return acc = acc + curr; + }, BigInt("0")); + const random = BigInt(Number(totalWeight) * Math.random()); + const weightRandomIndex = getWeightRandom(weightsScores, random); + return relayers[weightRandomIndex]; +} +class RelayerClient { + constructor({ netId, config, Aggregator, fetchDataOptions: fetchDataOptions2 }) { + this.netId = netId; + this.config = config; + this.Aggregator = Aggregator; + this.fetchDataOptions = fetchDataOptions2; + } + askRelayerStatus(_0) { + return __async$3(this, arguments, function* ({ + hostname, + relayerAddress + }) { + var _a, _b; + const url = `https://${!hostname.endsWith("/") ? hostname + "/" : hostname}`; + const rawStatus = yield fetchData(`${url}status`, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + headers: { + "Content-Type": "application/json, application/x-www-form-urlencoded" + }, + timeout: ((_a = this.fetchDataOptions) == null ? void 0 : _a.torPort) ? 1e4 : 3e3, + maxRetry: ((_b = this.fetchDataOptions) == null ? void 0 : _b.torPort) ? 2 : 0 + })); + const statusValidator = ajv.compile(getStatusSchema(this.netId, this.config)); + if (!statusValidator(rawStatus)) { + throw new Error("Invalid status schema"); + } + const status = __spreadProps$1(__spreadValues$1({}, rawStatus), { + url + }); + if (status.currentQueue > 5) { + throw new Error("Withdrawal queue is overloaded"); + } + if (status.netId !== this.netId) { + throw new Error("This relayer serves a different network"); + } + if (relayerAddress && this.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) { + throw new Error("The Relayer reward address must match registered address"); + } + if (!isRelayerUpdated(status.version, this.netId)) { + throw new Error("Outdated version."); + } + return status; + }); + } + filterRelayer(curr, relayer, subdomains, debugRelayer = false) { + return __async$3(this, null, function* () { + var _a; + const { ensSubdomainKey } = this.config; + const subdomainIndex = subdomains.indexOf(ensSubdomainKey); + const mainnetSubdomain = curr.records[0]; + const hostname = curr.records[subdomainIndex]; + const isHostWithProtocol = hostname.includes("http"); + const { owner, balance: stakeBalance, isRegistered } = curr; + const { ensName, relayerAddress } = relayer; + const isOwner = !relayerAddress || relayerAddress === owner; + const hasMinBalance = stakeBalance >= MIN_STAKE_BALANCE; + const preCondition = hostname && isOwner && mainnetSubdomain && isRegistered && hasMinBalance && !isHostWithProtocol; + if (preCondition || debugRelayer) { + try { + const status = yield this.askRelayerStatus({ hostname, relayerAddress }); + return { + netId: status.netId, + url: status.url, + hostname, + ensName, + stakeBalance, + relayerAddress, + rewardAccount: ethers.getAddress(status.rewardAccount), + instances: getSupportedInstances(status.instances), + gasPrice: (_a = status.gasPrices) == null ? void 0 : _a.fast, + ethPrices: status.ethPrices, + currentQueue: status.currentQueue, + tornadoServiceFee: status.tornadoServiceFee + }; + } catch (err) { + if (debugRelayer) { + throw err; + } + return { + hostname, + relayerAddress, + errorMessage: err.message + }; + } + } else { + if (debugRelayer) { + const errMsg = `Relayer ${hostname} condition not met`; + throw new Error(errMsg); + } + return { + hostname, + relayerAddress, + errorMessage: `Relayer ${hostname} condition not met` + }; + } + }); + } + getValidRelayers(relayers, subdomains, debugRelayer = false) { + return __async$3(this, null, function* () { + const relayersSet = /* @__PURE__ */ new Set(); + const uniqueRelayers = relayers.reverse().filter(({ ensName }) => { + if (!relayersSet.has(ensName)) { + relayersSet.add(ensName); + return true; + } + return false; + }); + const relayerNameHashes = uniqueRelayers.map((r) => ethers.namehash(r.ensName)); + const relayersData = yield this.Aggregator.relayersData.staticCall(relayerNameHashes, subdomains); + const invalidRelayers = []; + const validRelayers = (yield Promise.all( + relayersData.map((curr, index) => this.filterRelayer(curr, uniqueRelayers[index], subdomains, debugRelayer)) + )).filter((r) => { + if (r.errorMessage) { + invalidRelayers.push(r); + return false; + } + return true; + }); + return { + validRelayers, + invalidRelayers + }; + }); + } + pickWeightedRandomRelayer(relayers) { + return pickWeightedRandomRelayer(relayers, this.netId); + } + tornadoWithdraw(_0) { + return __async$3(this, arguments, function* ({ contract, proof, args }) { + const { url } = this.selectedRelayer; + const withdrawResponse = yield fetchData(`${url}v1/tornadoWithdraw`, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + contract, + proof, + args + }) + })); + const { id, error } = withdrawResponse; + if (error) { + throw new Error(error); + } + let relayerStatus; + const jobUrl = `${url}v1/jobs/${id}`; + console.log(`Job submitted: ${jobUrl} +`); + while (!relayerStatus || !["FAILED", "CONFIRMED"].includes(relayerStatus)) { + const jobResponse = yield fetchData(jobUrl, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + method: "GET", + headers: { + "Content-Type": "application/json" + } + })); + if (jobResponse.error) { + throw new Error(error); + } + const jobValidator = ajv.compile(jobsSchema); + if (!jobValidator(jobResponse)) { + const errMsg = `${jobUrl} has an invalid job response`; + throw new Error(errMsg); + } + const { status, txHash, confirmations, failedReason } = jobResponse; + if (relayerStatus !== status) { + if (status === "FAILED") { + const errMsg = `Job ${status}: ${jobUrl} failed reason: ${failedReason}`; + throw new Error(errMsg); + } else if (status === "SENT") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash} +`); + } else if (status === "MINED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else if (status === "CONFIRMED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else { + console.log(`Job ${status}: ${jobUrl} +`); + } + relayerStatus = status; + } + yield sleep(3e3); + } + }); + } +} + +var __async$2 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function getTokenBalances(_0) { + return __async$2(this, arguments, function* ({ + provider, + Multicall: Multicall2, + currencyName, + userAddress, + tokenAddresses = [] + }) { + const tokenCalls = tokenAddresses.map((tokenAddress) => { + const Token = ERC20__factory.connect(tokenAddress, provider); + return [ + { + contract: Token, + name: "balanceOf", + params: [userAddress] + }, + { + contract: Token, + name: "name" + }, + { + contract: Token, + name: "symbol" + }, + { + contract: Token, + name: "decimals" + } + ]; + }).flat(); + const multicallResults = yield multicall(Multicall2, [ + { + contract: Multicall2, + name: "getEthBalance", + params: [userAddress] + }, + ...tokenCalls.length ? tokenCalls : [] + ]); + const ethResults = multicallResults[0]; + const tokenResults = multicallResults.slice(1).length ? chunk(multicallResults.slice(1), tokenCalls.length / tokenAddresses.length) : []; + const tokenBalances = tokenResults.map((tokenResult, index) => { + const [tokenBalance, tokenName, tokenSymbol, tokenDecimals] = tokenResult; + const tokenAddress = tokenAddresses[index]; + return { + address: tokenAddress, + name: tokenName, + symbol: tokenSymbol, + decimals: Number(tokenDecimals), + balance: tokenBalance + }; + }); + return [ + { + address: ethers.ZeroAddress, + name: currencyName, + symbol: currencyName, + decimals: 18, + balance: ethResults + }, + ...tokenBalances + ]; + }); +} + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; +}; +var __async$1 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class TreeCache { + constructor({ netId, amount, currency, userDirectory, PARTS_COUNT = 4 }) { + this.netId = netId; + this.amount = amount; + this.currency = currency; + this.userDirectory = userDirectory; + this.PARTS_COUNT = PARTS_COUNT; + } + getInstanceName() { + return `deposits_${this.netId}_${this.currency}_${this.amount}`; + } + createTree(events, tree) { + return __async$1(this, null, function* () { + const bloom = new BloomFilter(events.length); + console.log(`Creating cached tree for ${this.getInstanceName()} +`); + const eventsData = events.reduce( + (acc, _a, i) => { + var _b = _a, { leafIndex, commitment } = _b, rest = __objRest(_b, ["leafIndex", "commitment"]); + if (leafIndex !== i) { + throw new Error(`leafIndex (${leafIndex}) !== i (${i})`); + } + acc[commitment] = __spreadProps(__spreadValues({}, rest), { leafIndex }); + return acc; + }, + {} + ); + const slices = tree.getTreeSlices(this.PARTS_COUNT); + yield Promise.all( + slices.map((slice, index) => __async$1(this, null, function* () { + const metadata = slice.elements.reduce((acc, curr) => { + if (index < this.PARTS_COUNT - 1) { + bloom.add(curr); + } + acc.push(eventsData[curr]); + return acc; + }, []); + const dataString2 = JSON.stringify( + __spreadProps(__spreadValues({}, slice), { + metadata + }), + null, + 2 + ) + "\n"; + const fileName2 = `${this.getInstanceName()}_slice${index + 1}.json`; + yield saveUserFile({ + fileName: fileName2, + userDirectory: this.userDirectory, + dataString: dataString2 + }); + })) + ); + const dataString = bloom.serialize() + "\n"; + const fileName = `${this.getInstanceName()}_bloom.json`; + yield saveUserFile({ + fileName, + userDirectory: this.userDirectory, + dataString + }); + }); + } +} + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +let groth16; +const groth16Promise = (() => __async(void 0, null, function* () { + if (!groth16) { + groth16 = yield websnarkGroth({ wasmInitialMemory: 2e3 }); + } +}))(); +function calculateSnarkProof(input, circuit, provingKey) { + return __async(this, null, function* () { + yield groth16Promise; + const snarkInput = { + root: input.root, + nullifierHash: BigInt(input.nullifierHex).toString(), + recipient: BigInt(input.recipient), + relayer: BigInt(input.relayer), + fee: input.fee, + refund: input.refund, + nullifier: input.nullifier, + secret: input.secret, + pathElements: input.pathElements, + pathIndices: input.pathIndices + }; + console.log("Start generating SNARK proof", snarkInput); + console.time("SNARK proof time"); + const proofData = yield websnarkUtils__namespace.genWitnessAndProve(groth16, snarkInput, circuit, provingKey); + const proof = websnarkUtils__namespace.toSolidityInput(proofData).proof; + console.timeEnd("SNARK proof time"); + const args = [ + toFixedHex(input.root, 32), + toFixedHex(input.nullifierHex, 32), + input.recipient, + input.relayer, + toFixedHex(input.fee, 32), + toFixedHex(input.refund, 32) + ]; + return { proof, args }; + }); +} + +exports.BaseDepositsService = BaseDepositsService; +exports.BaseEchoService = BaseEchoService; +exports.BaseEncryptedNotesService = BaseEncryptedNotesService; +exports.BaseEventsService = BaseEventsService; +exports.BaseGovernanceService = BaseGovernanceService; +exports.BaseRegistryService = BaseRegistryService; +exports.BatchBlockService = BatchBlockService; +exports.BatchEventsService = BatchEventsService; +exports.BatchTransactionService = BatchTransactionService; +exports.DEPOSIT = DEPOSIT; +exports.Deposit = Deposit; +exports.ENS__factory = ENS__factory; +exports.ERC20__factory = ERC20__factory; +exports.GET_DEPOSITS = GET_DEPOSITS; +exports.GET_ECHO_EVENTS = GET_ECHO_EVENTS; +exports.GET_ENCRYPTED_NOTES = GET_ENCRYPTED_NOTES; +exports.GET_GOVERNANCE_APY = GET_GOVERNANCE_APY; +exports.GET_GOVERNANCE_EVENTS = GET_GOVERNANCE_EVENTS; +exports.GET_NOTE_ACCOUNTS = GET_NOTE_ACCOUNTS; +exports.GET_REGISTERED = GET_REGISTERED; +exports.GET_STATISTIC = GET_STATISTIC; +exports.GET_WITHDRAWALS = GET_WITHDRAWALS; +exports.GasPriceOracle__factory = GasPriceOracle__factory; +exports.Invoice = Invoice; +exports.MIN_STAKE_BALANCE = MIN_STAKE_BALANCE; +exports.MerkleTreeService = MerkleTreeService; +exports.Mimc = Mimc; +exports.Multicall__factory = Multicall__factory; +exports.NetId = NetId; +exports.NodeDepositsService = NodeDepositsService; +exports.NodeEchoService = NodeEchoService; +exports.NodeEncryptedNotesService = NodeEncryptedNotesService; +exports.NodeGovernanceService = NodeGovernanceService; +exports.NodeRegistryService = NodeRegistryService; +exports.NoteAccount = NoteAccount; +exports.OffchainOracle__factory = OffchainOracle__factory; +exports.OvmGasPriceOracle__factory = OvmGasPriceOracle__factory; +exports.Pedersen = Pedersen; +exports.RelayerClient = RelayerClient; +exports.ReverseRecords__factory = ReverseRecords__factory; +exports.TokenPriceOracle = TokenPriceOracle; +exports.TornadoBrowserProvider = TornadoBrowserProvider; +exports.TornadoFeeOracle = TornadoFeeOracle; +exports.TornadoRpcSigner = TornadoRpcSigner; +exports.TornadoVoidSigner = TornadoVoidSigner; +exports.TornadoWallet = TornadoWallet; +exports.TreeCache = TreeCache; +exports.WITHDRAWAL = WITHDRAWAL; +exports._META = _META; +exports.addNetwork = addNetwork; +exports.ajv = ajv; +exports.base64ToBytes = base64ToBytes; +exports.bigIntReplacer = bigIntReplacer; +exports.bnToBytes = bnToBytes; +exports.buffPedersenHash = buffPedersenHash; +exports.bufferToBytes = bufferToBytes; +exports.bytesToBN = bytesToBN; +exports.bytesToBase64 = bytesToBase64; +exports.bytesToHex = bytesToHex; +exports.calculateScore = calculateScore; +exports.calculateSnarkProof = calculateSnarkProof; +exports.chunk = chunk; +exports.concatBytes = concatBytes; +exports.convertETHToTokenAmount = convertETHToTokenAmount; +exports.createDeposit = createDeposit; +exports.crypto = crypto; +exports.defaultConfig = defaultConfig; +exports.defaultUserAgent = defaultUserAgent; +exports.download = download; +exports.enabledChains = enabledChains; +exports.existsAsync = existsAsync; +exports.factories = index; +exports.fetch = fetch; +exports.fetchData = fetchData; +exports.fetchGetUrlFunc = fetchGetUrlFunc; +exports.getAllDeposits = getAllDeposits; +exports.getAllEncryptedNotes = getAllEncryptedNotes; +exports.getAllGovernanceEvents = getAllGovernanceEvents; +exports.getAllGraphEchoEvents = getAllGraphEchoEvents; +exports.getAllRegisters = getAllRegisters; +exports.getAllWithdrawals = getAllWithdrawals; +exports.getConfig = getConfig; +exports.getDeposits = getDeposits; +exports.getEncryptedNotes = getEncryptedNotes; +exports.getGasOraclePlugin = getGasOraclePlugin; +exports.getGovernanceEvents = getGovernanceEvents; +exports.getGraphEchoEvents = getGraphEchoEvents; +exports.getHttpAgent = getHttpAgent; +exports.getInstanceByAddress = getInstanceByAddress; +exports.getMeta = getMeta; +exports.getNetworkConfig = getNetworkConfig; +exports.getNoteAccounts = getNoteAccounts; +exports.getProvider = getProvider; +exports.getProviderWithNetId = getProviderWithNetId; +exports.getRegisters = getRegisters; +exports.getStatistic = getStatistic; +exports.getStatusSchema = getStatusSchema; +exports.getSubdomains = getSubdomains; +exports.getSupportedInstances = getSupportedInstances; +exports.getTokenBalances = getTokenBalances; +exports.getWeightRandom = getWeightRandom; +exports.getWithdrawals = getWithdrawals; +exports.hexToBytes = hexToBytes; +exports.isNode = isNode; +exports.isRelayerUpdated = isRelayerUpdated; +exports.jobsSchema = jobsSchema; +exports.leBuff2Int = leBuff2Int; +exports.leInt2Buff = leInt2Buff; +exports.loadCachedEvents = loadCachedEvents; +exports.loadSavedEvents = loadSavedEvents; +exports.mimc = mimc; +exports.multicall = multicall; +exports.packEncryptedMessage = packEncryptedMessage; +exports.parseAddress = parseAddress; +exports.parseKey = parseKey; +exports.parseMnemonic = parseMnemonic; +exports.parseNumber = parseNumber; +exports.parseRecoveryKey = parseRecoveryKey; +exports.parseRelayer = parseRelayer; +exports.parseSemanticVersion = parseSemanticVersion; +exports.parseUrl = parseUrl; +exports.pedersen = pedersen; +exports.pickWeightedRandomRelayer = pickWeightedRandomRelayer; +exports.populateTransaction = populateTransaction; +exports.queryGraph = queryGraph; +exports.rBigInt = rBigInt; +exports.saveUserFile = saveUserFile; +exports.sleep = sleep; +exports.substring = substring; +exports.toFixedHex = toFixedHex; +exports.toFixedLength = toFixedLength; +exports.unpackEncryptedMessage = unpackEncryptedMessage; +exports.unzipAsync = unzipAsync; +exports.validateUrl = validateUrl; +exports.zipAsync = zipAsync; diff --git a/dist/index.mjs b/dist/index.mjs new file mode 100644 index 0000000..a2be197 --- /dev/null +++ b/dist/index.mjs @@ -0,0 +1,7842 @@ +import { Interface, Contract, FetchUrlFeeDataNetworkPlugin, FetchRequest, Network, EnsPlugin, GasCostPlugin, JsonRpcProvider, Wallet, HDNodeWallet, VoidSigner, JsonRpcSigner, BrowserProvider, parseUnits, FeeData, getAddress, computeAddress, Transaction, Mnemonic, parseEther, namehash, ZeroAddress } from 'ethers'; +import crossFetch from 'cross-fetch'; +import { HttpProxyAgent } from 'http-proxy-agent'; +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { SocksProxyAgent } from 'socks-proxy-agent'; +import { webcrypto } from 'crypto'; +import BN from 'bn.js'; +import Table from 'cli-table3'; +import moment from 'moment'; +import path from 'path'; +import { stat, mkdir, writeFile, readFile } from 'fs/promises'; +import { zip, unzip } from 'fflate'; +import Ajv from 'ajv'; +import { buildPedersenHash, buildMimcSponge } from 'circomlibjs'; +import { getEncryptionPublicKey, encrypt, decrypt } from '@metamask/eth-sig-util'; +import { Worker as Worker$1 } from 'worker_threads'; +import { MerkleTree, PartialMerkleTree } from '@tornado/fixed-merkle-tree'; +import { InvalidArgumentError } from 'commander'; +import BloomFilter from 'bloomfilter.js'; +import * as websnarkUtils from '@tornado/websnark/src/utils'; +import websnarkGroth from '@tornado/websnark/src/groth16'; + +const _abi$6 = [ + { + constant: true, + inputs: [ + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "supportsInterface", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "pure", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + }, + { + internalType: "string", + name: "value", + type: "string" + } + ], + name: "setText", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "interfaceImplementer", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentTypes", + type: "uint256" + } + ], + name: "ABI", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + }, + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "setPubkey", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "setContenthash", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "addr", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "setAuthorisation", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + } + ], + name: "text", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentType", + type: "uint256" + }, + { + internalType: "bytes", + name: "data", + type: "bytes" + } + ], + name: "setABI", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "name", + type: "string" + } + ], + name: "setName", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + internalType: "bytes", + name: "a", + type: "bytes" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "contenthash", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "pubkey", + outputs: [ + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "a", + type: "address" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "setInterface", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + } + ], + name: "addr", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + }, + { + internalType: "address", + name: "", + type: "address" + }, + { + internalType: "address", + name: "", + type: "address" + } + ], + name: "authorisations", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + payable: false, + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "target", + type: "address" + }, + { + indexed: false, + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "AuthorisationChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "indexedKey", + type: "string" + }, + { + indexed: false, + internalType: "string", + name: "key", + type: "string" + } + ], + name: "TextChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "PubkeyChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "name", + type: "string" + } + ], + name: "NameChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + indexed: false, + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "InterfaceChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "ContenthashChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "address", + name: "a", + type: "address" + } + ], + name: "AddrChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + indexed: false, + internalType: "bytes", + name: "newAddress", + type: "bytes" + } + ], + name: "AddressChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "uint256", + name: "contentType", + type: "uint256" + } + ], + name: "ABIChanged", + type: "event" + } +]; +class ENS__factory { + static createInterface() { + return new Interface(_abi$6); + } + static connect(address, runner) { + return new Contract(address, _abi$6, runner); + } +} +ENS__factory.abi = _abi$6; + +const _abi$5 = [ + { + constant: true, + inputs: [], + name: "totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "_totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "who", + type: "address" + } + ], + name: "balanceOf", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "symbol", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transfer", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "spender", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Approval", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "from", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "to", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Transfer", + type: "event" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + } + ], + name: "allowance", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "from", + type: "address" + }, + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transferFrom", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "approve", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + } + ], + name: "nonces", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "amount", + type: "uint256" + }, + { + internalType: "uint256", + name: "deadline", + type: "uint256" + }, + { + internalType: "uint8", + name: "v", + type: "uint8" + }, + { + internalType: "bytes32", + name: "r", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "s", + type: "bytes32" + } + ], + name: "permit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class ERC20__factory { + static createInterface() { + return new Interface(_abi$5); + } + static connect(address, runner) { + return new Contract(address, _abi$5, runner); + } +} +ERC20__factory.abi = _abi$5; + +const _abi$4 = [ + { + inputs: [], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "GAS_UNIT", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_derivationThresold", + type: "uint32" + } + ], + name: "changeDerivationThresold", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasUnit", + type: "uint32" + } + ], + name: "changeGasUnit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_heartbeat", + type: "uint32" + } + ], + name: "changeHeartbeat", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + name: "changeOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "derivationThresold", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "heartbeat", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxPriorityFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "pastGasPrice", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasPrice", + type: "uint32" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "timestamp", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + } +]; +class GasPriceOracle__factory { + static createInterface() { + return new Interface(_abi$4); + } + static connect(address, runner) { + return new Contract(address, _abi$4, runner); + } +} +GasPriceOracle__factory.abi = _abi$4; + +const _abi$3 = [ + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes[]", + name: "returnData", + type: "bytes[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3Value[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3Value", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "blockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [], + name: "getBasefee", + outputs: [ + { + internalType: "uint256", + name: "basefee", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + name: "getBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getBlockNumber", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getChainId", + outputs: [ + { + internalType: "uint256", + name: "chainid", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockCoinbase", + outputs: [ + { + internalType: "address", + name: "coinbase", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockDifficulty", + outputs: [ + { + internalType: "uint256", + name: "difficulty", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockGasLimit", + outputs: [ + { + internalType: "uint256", + name: "gaslimit", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockTimestamp", + outputs: [ + { + internalType: "uint256", + name: "timestamp", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "addr", + type: "address" + } + ], + name: "getEthBalance", + outputs: [ + { + internalType: "uint256", + name: "balance", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getLastBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryAggregate", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryBlockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + } +]; +class Multicall__factory { + static createInterface() { + return new Interface(_abi$3); + } + static connect(address, runner) { + return new Contract(address, _abi$3, runner); + } +} +Multicall__factory.abi = _abi$3; + +const _abi$2 = [ + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + }, + { + internalType: "contract IOracle[]", + name: "existingOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + }, + { + internalType: "contract IERC20[]", + name: "existingConnectors", + type: "address[]" + }, + { + internalType: "contract IERC20", + name: "wBase", + type: "address" + }, + { + internalType: "address", + name: "owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "ArraysLengthMismatch", + type: "error" + }, + { + inputs: [], + name: "ConnectorAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "InvalidOracleTokenKind", + type: "error" + }, + { + inputs: [], + name: "OracleAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "SameTokens", + type: "error" + }, + { + inputs: [], + name: "TooBigThreshold", + type: "error" + }, + { + inputs: [], + name: "UnknownConnector", + type: "error" + }, + { + inputs: [], + name: "UnknownOracle", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract MultiWrapper", + name: "multiWrapper", + type: "address" + } + ], + name: "MultiWrapperUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "addConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "addOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "connectors", + outputs: [ + { + internalType: "contract IERC20[]", + name: "allConnectors", + type: "address[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + } + ], + name: "getRate", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + } + ], + name: "getRateToEth", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "multiWrapper", + outputs: [ + { + internalType: "contract MultiWrapper", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "oracles", + outputs: [ + { + internalType: "contract IOracle[]", + name: "allOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "removeConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "removeOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + } + ], + name: "setMultiWrapper", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OffchainOracle__factory { + static createInterface() { + return new Interface(_abi$2); + } + static connect(address, runner) { + return new Contract(address, _abi$2, runner); + } +} +OffchainOracle__factory.abi = _abi$2; + +const _abi$1 = [ + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "DecimalsUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "GasPriceUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "L1BaseFeeUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "OverheadUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "ScalarUpdated", + type: "event" + }, + { + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1Fee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1GasUsed", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "l1BaseFee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "overhead", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "scalar", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_decimals", + type: "uint256" + } + ], + name: "setDecimals", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_gasPrice", + type: "uint256" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_baseFee", + type: "uint256" + } + ], + name: "setL1BaseFee", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_overhead", + type: "uint256" + } + ], + name: "setOverhead", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_scalar", + type: "uint256" + } + ], + name: "setScalar", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OvmGasPriceOracle__factory { + static createInterface() { + return new Interface(_abi$1); + } + static connect(address, runner) { + return new Contract(address, _abi$1, runner); + } +} +OvmGasPriceOracle__factory.abi = _abi$1; + +const _abi = [ + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + internalType: "address[]", + name: "addresses", + type: "address[]" + } + ], + name: "getNames", + outputs: [ + { + internalType: "string[]", + name: "r", + type: "string[]" + } + ], + stateMutability: "view", + type: "function" + } +]; +class ReverseRecords__factory { + static createInterface() { + return new Interface(_abi); + } + static connect(address, runner) { + return new Contract(address, _abi, runner); + } +} +ReverseRecords__factory.abi = _abi; + +var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + ENS__factory: ENS__factory, + ERC20__factory: ERC20__factory, + GasPriceOracle__factory: GasPriceOracle__factory, + Multicall__factory: Multicall__factory, + OffchainOracle__factory: OffchainOracle__factory, + OvmGasPriceOracle__factory: OvmGasPriceOracle__factory, + ReverseRecords__factory: ReverseRecords__factory +}); + +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; +const crypto = isNode ? webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new BN(bytes, 16, "le"); +} +function leInt2Buff(bigint) { + return Uint8Array.from(new BN(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + +var __async$e = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function multicall(Multicall2, calls) { + return __async$e(this, null, function* () { + const calldata = calls.map((call) => { + var _a, _b, _c; + const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; + const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; + return { + target, + callData: callInterface.encodeFunctionData(call.name, call.params), + allowFailure: (_c = call.allowFailure) != null ? _c : false + }; + }); + const returnData = yield Multicall2.aggregate3.staticCall(calldata); + const res = returnData.map((call, i) => { + var _a; + const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; + const [result, data] = call; + const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; + return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; + }); + return res; + }); +} + +var __defProp$5 = Object.defineProperty; +var __defProps$4 = Object.defineProperties; +var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols; +var __getProtoOf$1 = Object.getPrototypeOf; +var __hasOwnProp$5 = Object.prototype.hasOwnProperty; +var __propIsEnum$5 = Object.prototype.propertyIsEnumerable; +var __reflectGet$1 = Reflect.get; +var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$5 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + if (__getOwnPropSymbols$5) + for (var prop of __getOwnPropSymbols$5(b)) { + if (__propIsEnum$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b)); +var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); +var __async$d = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +const fetch = crossFetch; +function getHttpAgent({ + fetchUrl, + proxyUrl, + torPort, + retry +}) { + if (torPort) { + return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); + } + if (!proxyUrl) { + return; + } + const isHttps = fetchUrl.includes("https://"); + if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { + return new SocksProxyAgent(proxyUrl); + } + if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { + if (isHttps) { + return new HttpsProxyAgent(proxyUrl); + } + return new HttpProxyAgent(proxyUrl); + } +} +function fetchData(_0) { + return __async$d(this, arguments, function* (url, options = {}) { + var _a, _b, _c; + const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; + const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; + const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; + let retry = 0; + let errorObject; + if (!options.method) { + if (!options.body) { + options.method = "GET"; + } else { + options.method = "POST"; + } + } + if (!options.headers) { + options.headers = {}; + } + if (isNode && !options.headers["User-Agent"]) { + options.headers["User-Agent"] = userAgent; + } + while (retry < MAX_RETRY + 1) { + let timeout; + if (!options.signal && options.timeout) { + const controller = new AbortController(); + options.signal = controller.signal; + timeout = setTimeout(() => { + controller.abort(); + }, options.timeout); + } + if (!options.agent && isNode && (options.proxy || options.torPort)) { + options.agent = getHttpAgent({ + fetchUrl: url, + proxyUrl: options.proxy, + torPort: options.torPort, + retry + }); + } + if (options.debug && typeof options.debug === "function") { + options.debug("request", { + url, + retry, + errorObject, + options + }); + } + try { + const resp = yield fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + redirect: options.redirect, + signal: options.signal, + agent: options.agent + }); + if (options.debug && typeof options.debug === "function") { + options.debug("response", resp); + } + if (!resp.ok) { + const errMsg = `Request to ${url} failed with error code ${resp.status}: +` + (yield resp.text()); + throw new Error(errMsg); + } + if (options.returnResponse) { + return resp; + } + const contentType = resp.headers.get("content-type"); + if (contentType == null ? void 0 : contentType.includes("application/json")) { + return yield resp.json(); + } + if (contentType == null ? void 0 : contentType.includes("text")) { + return yield resp.text(); + } + return resp; + } catch (error) { + if (timeout) { + clearTimeout(timeout); + } + errorObject = error; + retry++; + yield sleep(RETRY_ON); + } finally { + if (timeout) { + clearTimeout(timeout); + } + } + } + if (options.debug && typeof options.debug === "function") { + options.debug("error", errorObject); + } + throw errorObject; + }); +} +const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$d(void 0, null, function* () { + let signal; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { + controller.abort(); + }); + } + const init = __spreadProps$4(__spreadValues$5({}, options), { + method: req.method || "POST", + headers: req.headers, + body: req.body || void 0, + signal, + returnResponse: true + }); + const resp = yield fetchData(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = yield resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; +}); +const oracleMapper = /* @__PURE__ */ new Map(); +const multicallMapper = /* @__PURE__ */ new Map(); +function getGasOraclePlugin(networkKey, fetchOptions) { + const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; + return new FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async$d(this, null, function* () { + if (!oracleMapper.has(networkKey)) { + oracleMapper.set(networkKey, GasPriceOracle__factory.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); + } + if (!multicallMapper.has(networkKey)) { + multicallMapper.set( + networkKey, + Multicall__factory.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) + ); + } + const Oracle = oracleMapper.get(networkKey); + const Multicall2 = multicallMapper.get(networkKey); + const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield multicall(Multicall2, [ + { + contract: Oracle, + name: "timestamp" + }, + { + contract: Oracle, + name: "heartbeat" + }, + { + contract: Oracle, + name: "maxFeePerGas" + }, + { + contract: Oracle, + name: "maxPriorityFeePerGas" + } + ]); + const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); + if (!isOutdated) { + const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); + const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; + return { + gasPrice: maxFeePerGas, + maxFeePerGas, + maxPriorityFeePerGas + }; + } + const fetchReq = new FetchRequest(gasStationApi); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + if (isNode) { + fetchReq.setHeader("User-Agent", "ethers"); + } + const [ + { + bodyJson: { fast } + }, + { gasPrice } + ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); + return { + gasPrice, + maxFeePerGas: parseUnits(`${fast.maxFee}`, 9), + maxPriorityFeePerGas: parseUnits(`${fast.maxPriorityFee}`, 9) + }; + })); +} +function getProvider(rpcUrl, fetchOptions) { + return __async$d(this, null, function* () { + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const _staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); + const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); + const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); + const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + const staticNetwork = new Network(_staticNetwork.name, _staticNetwork.chainId); + if (ensPlugin) { + staticNetwork.attachPlugin(ensPlugin); + } + if (gasCostPlugin) { + staticNetwork.attachPlugin(gasCostPlugin); + } + if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { + staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); + } else if (gasStationPlugin) { + staticNetwork.attachPlugin(gasStationPlugin); + } + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; + return provider; + }); +} +function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { + const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; + const hasEns = Boolean(reverseRecordsContract); + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = new Network(networkName, netId); + if (hasEns) { + staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); + } + staticNetwork.attachPlugin(new GasCostPlugin()); + if (gasPriceOracleContract) { + staticNetwork.attachPlugin( + getGasOraclePlugin(`${netId}_${rpcUrl}`, { + gasPriceOracle: gasPriceOracleContract, + gasStationApi + }) + ); + } + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; + return provider; +} +const populateTransaction = (signer, tx) => __async$d(void 0, null, function* () { + const provider = signer.provider; + if (!tx.from) { + tx.from = signer.address; + } else if (tx.from !== signer.address) { + const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; + throw new Error(errMsg); + } + const [feeData, nonce] = yield Promise.all([ + (() => __async$d(void 0, null, function* () { + if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + return new FeeData(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); + } + if (tx.gasPrice) { + return new FeeData(BigInt(tx.gasPrice), null, null); + } + const fetchedFeeData = yield provider.getFeeData(); + if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { + return new FeeData( + null, + fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + fetchedFeeData.maxPriorityFeePerGas + ); + } else { + return new FeeData( + fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + null, + null + ); + } + }))(), + (() => __async$d(void 0, null, function* () { + if (tx.nonce) { + return tx.nonce; + } + let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); + if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { + console.log( + `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` + ); + fetchedNonce++; + } + return fetchedNonce; + }))() + ]); + tx.nonce = nonce; + if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { + tx.maxFeePerGas = feeData.maxFeePerGas; + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + if (!tx.type) { + tx.type = 2; + } + delete tx.gasPrice; + } else if (feeData.gasPrice) { + tx.gasPrice = feeData.gasPrice; + if (!tx.type) { + tx.type = 0; + } + delete tx.maxFeePerGas; + delete tx.maxPriorityFeePerGas; + } + tx.gasLimit = tx.gasLimit || (yield (() => __async$d(void 0, null, function* () { + try { + const gasLimit = yield provider.estimateGas(tx); + return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); + } catch (err) { + if (signer.gasFailover) { + console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + return BigInt("3000000"); + } + throw err; + } + }))()); + return tx; +}); +class TornadoWallet extends Wallet { + constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(key, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + static fromMnemonic(mneomnic, provider, index = 0, options) { + const defaultPath = `m/44'/60'/0'/0/${index}`; + const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); + return new TornadoWallet(privateKey, provider, options); + } + populateTransaction(tx) { + return __async$d(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoVoidSigner extends VoidSigner { + constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(address, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + populateTransaction(tx) { + return __async$d(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet$1(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoRpcSigner extends JsonRpcSigner { + constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(provider, address); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + sendUncheckedTransaction(tx) { + return __async$d(this, null, function* () { + return __superGet$1(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); + }); + } +} +class TornadoBrowserProvider extends BrowserProvider { + constructor(ethereum, network, options) { + super(ethereum, network); + this.options = options; + } + getSigner(address) { + return __async$d(this, null, function* () { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const signerAddress = (yield __superGet$1(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; + if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$1(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { + yield this.options.connectWallet(); + } + if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { + (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); + } + if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { + (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); + } + if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { + (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); + } + return new TornadoRpcSigner(this, signerAddress, this.options); + }); + } +} + +const GET_STATISTIC = ` + query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { + deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { + index + timestamp + blockNumber + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const _META = ` + query getMeta { + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_REGISTERED = ` + query getRegistered($first: Int, $fromBlock: Int) { + relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { + blockRegistration_gte: $fromBlock + }) { + id + address + ensName + blockRegistration + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_DEPOSITS = ` + query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { + deposits(first: $first, orderBy: index, orderDirection: asc, where: { + amount: $amount, + currency: $currency, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + commitment + index + timestamp + from + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_WITHDRAWALS = ` + query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { + withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { + currency: $currency, + amount: $amount, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + nullifier + to + fee + timestamp + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_NOTE_ACCOUNTS = ` + query getNoteAccount($address: String!) { + noteAccounts(where: { address: $address }) { + id + index + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ECHO_EVENTS = ` + query getNoteAccounts($first: Int, $fromBlock: Int) { + noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + id + blockNumber + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ENCRYPTED_NOTES = ` + query getEncryptedNotes($first: Int, $fromBlock: Int) { + encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + index + transactionHash + encryptedNote + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_EVENTS = ` + query getGovernanceEvents($first: Int, $fromBlock: Int) { + proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + proposer + target + startTime + endTime + description + } + votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + voter + support + votes + from + input + } + delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateTo + } + undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateFrom + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_APY = ` + stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { + id + date + dailyAmountBurned + } +`; + +var __defProp$4 = Object.defineProperty; +var __defProps$3 = Object.defineProperties; +var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; +var __hasOwnProp$4 = Object.prototype.hasOwnProperty; +var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$4 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + if (__getOwnPropSymbols$4) + for (var prop of __getOwnPropSymbols$4(b)) { + if (__propIsEnum$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); +var __async$c = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; +const first = 1e3; +function queryGraph(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + query, + variables, + fetchDataOptions: fetchDataOptions2 + }) { + var _a; + const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; + const { data, errors } = yield fetchData(graphUrl, __spreadProps$3(__spreadValues$4({}, fetchDataOptions2), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + query, + variables + }) + })); + if (errors) { + throw new Error(JSON.stringify(errors)); + } + if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { + throw new Error("Subgraph has indexing errors"); + } + return data; + }); +} +function getStatistic(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + deposits, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_STATISTIC, + variables: { + currency, + first: 10, + orderBy: "index", + orderDirection: "desc", + amount + }, + fetchDataOptions: fetchDataOptions2 + }); + const events = deposits.map((e) => ({ + timestamp: Number(e.timestamp), + leafIndex: Number(e.index), + blockNumber: Number(e.blockNumber) + })).reverse(); + const [lastEvent] = events.slice(-1); + return { + events, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getStatistic query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getMeta(_0) { + return __async$c(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { + try { + const { + _meta: { + block: { number: lastSyncBlock }, + hasIndexingErrors + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: _META, + fetchDataOptions: fetchDataOptions2 + }); + return { + lastSyncBlock, + hasIndexingErrors + }; + } catch (err) { + console.log("Error from getMeta query"); + console.log(err); + return { + lastSyncBlock: null, + hasIndexingErrors: null + }; + } + }); +} +function getRegisters({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_REGISTERED, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllRegisters(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + relayers: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Registers", + fromBlock: Number(firstEvent.blockRegistration), + toBlock: Number(lastEvent.blockRegistration), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); + fromBlock = Number(lastEvent.blockRegistration); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, address, ensName, blockRegistration }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockRegistration), + logIndex: Number(logIndex), + transactionHash, + ensName, + relayerAddress: getAddress(address) + }; + }); + return { + events: result, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllRegisters query"); + console.log(err); + return { events: [], lastSyncBlock: fromBlock }; + } + }); +} +function getDeposits({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_DEPOSITS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllDeposits(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + deposits: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Deposits", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + commitment, + leafIndex: Number(index), + timestamp: Number(timestamp), + from: getAddress(from) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllDeposits query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getWithdrawals({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_WITHDRAWALS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllWithdrawals(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + withdrawals: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Withdrawals", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + nullifierHash: nullifier, + to: getAddress(to), + fee, + timestamp: Number(timestamp) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllWithdrawals query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getNoteAccounts(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + address, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + noteAccounts: events, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_NOTE_ACCOUNTS, + variables: { + address: address.toLowerCase() + }, + fetchDataOptions: fetchDataOptions2 + }); + return { + events, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getNoteAccounts query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getGraphEchoEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ECHO_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGraphEchoEvents(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + noteAccounts: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EchoEvents", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => { + const [transactionHash, logIndex] = e.id.split("-"); + return { + blockNumber: Number(e.blockNumber), + logIndex: Number(logIndex), + transactionHash, + address: getAddress(e.address), + encryptedAccount: e.encryptedAccount + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGraphEchoEvents query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getEncryptedNotes({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ENCRYPTED_NOTES, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllEncryptedNotes(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + encryptedNotes: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EncryptedNotes", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => ({ + blockNumber: Number(e.blockNumber), + logIndex: Number(e.index), + transactionHash: e.transactionHash, + encryptedNote: e.encryptedNote + })); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllEncryptedNotes query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getGovernanceEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_GOVERNANCE_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGovernanceEvents(_0) { + return __async$c(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const result = []; + let lastSyncBlock = fromBlock; + while (true) { + const { + proposals, + votes, + delegates, + undelegates, + _meta: { + block: { number: currentBlock } + } + } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; + if (eventsLength === 0) { + break; + } + const formattedProposals = proposals.map( + ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "ProposalCreated", + id: Number(proposalId), + proposer: getAddress(proposer), + target: getAddress(target), + startTime: Number(startTime), + endTime: Number(endTime), + description + }; + } + ); + const formattedVotes = votes.map( + ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { + if (!input || input.length > 2048) { + input = ""; + } + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Voted", + proposalId: Number(proposalId), + voter: getAddress(voter), + support, + votes: votes2, + from: getAddress(from), + input + }; + } + ); + const formattedDelegates = delegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Delegated", + account: getAddress(account), + delegateTo: getAddress(delegateTo) + }; + } + ); + const formattedUndelegates = undelegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Undelegated", + account: getAddress(account), + delegateFrom: getAddress(delegateFrom) + }; + } + ); + let formattedEvents = [ + ...formattedProposals, + ...formattedVotes, + ...formattedDelegates, + ...formattedUndelegates + ].sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }); + if (eventsLength < 900) { + result.push(...formattedEvents); + break; + } + const [firstEvent] = formattedEvents; + const [lastEvent2] = formattedEvents.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Governance Events", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: eventsLength + }); + } + formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + result.push(...formattedEvents); + } + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGovernance query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} + +var graph = /*#__PURE__*/Object.freeze({ + __proto__: null, + GET_DEPOSITS: GET_DEPOSITS, + GET_ECHO_EVENTS: GET_ECHO_EVENTS, + GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES, + GET_GOVERNANCE_APY: GET_GOVERNANCE_APY, + GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS, + GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS, + GET_REGISTERED: GET_REGISTERED, + GET_STATISTIC: GET_STATISTIC, + GET_WITHDRAWALS: GET_WITHDRAWALS, + _META: _META, + getAllDeposits: getAllDeposits, + getAllEncryptedNotes: getAllEncryptedNotes, + getAllGovernanceEvents: getAllGovernanceEvents, + getAllGraphEchoEvents: getAllGraphEchoEvents, + getAllRegisters: getAllRegisters, + getAllWithdrawals: getAllWithdrawals, + getDeposits: getDeposits, + getEncryptedNotes: getEncryptedNotes, + getGovernanceEvents: getGovernanceEvents, + getGraphEchoEvents: getGraphEchoEvents, + getMeta: getMeta, + getNoteAccounts: getNoteAccounts, + getRegisters: getRegisters, + getStatistic: getStatistic, + getWithdrawals: getWithdrawals, + queryGraph: queryGraph +}); + +var __async$b = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class BatchBlockService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getBlock(blockTag) { + return __async$b(this, null, function* () { + const blockObject = yield this.provider.getBlock(blockTag); + if (!blockObject) { + const errMsg = `No block for ${blockTag}`; + throw new Error(errMsg); + } + return blockObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((blocks, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return (() => __async$b(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(blocks.map((b) => this.getBlock(b))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchBlocks(blocks) { + return __async$b(this, null, function* () { + let blockCount = 0; + const results = []; + for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + blockCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: blockCount / blocks.length, + currentIndex: blockCount, + totalIndex: blocks.length + }); + } + } + return results; + }); + } +} +class BatchTransactionService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getTransaction(txHash) { + return __async$b(this, null, function* () { + const txObject = yield this.provider.getTransaction(txHash); + if (!txObject) { + const errMsg = `No transaction for ${txHash}`; + throw new Error(errMsg); + } + return txObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((txs, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return (() => __async$b(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); + } catch (e) { + retries++; + err = e; + yield sleep(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchTransactions(txs) { + return __async$b(this, null, function* () { + let txCount = 0; + const results = []; + for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + txCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); + } + } + return results; + }); + } +} +class BatchEventsService { + constructor({ + provider, + contract, + onProgress, + concurrencySize = 10, + blocksPerRequest = 2e3, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.contract = contract; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.blocksPerRequest = blocksPerRequest; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getPastEvents(_0) { + return __async$b(this, arguments, function* ({ fromBlock, toBlock, type }) { + let err; + let retries = 0; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield this.contract.queryFilter(type, fromBlock, toBlock); + } catch (e) { + err = e; + retries++; + if (e.message.includes("after last accepted block")) { + const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); + toBlock = acceptedBlock; + } + yield sleep(this.retryOn); + } + } + throw err; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((event, index) => __async$b(this, null, function* () { + yield sleep(20 * index); + return this.getPastEvents(event); + })); + } + getBatchEvents(_0) { + return __async$b(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + const eventsToSync = []; + for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { + const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; + eventsToSync.push({ fromBlock: i, toBlock: j, type }); + } + const events = []; + const eventChunk = chunk(eventsToSync, this.concurrencySize); + let chunkCount = 0; + for (const chunk2 of eventChunk) { + chunkCount++; + const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); + events.push(...fetchedEvents); + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: chunkCount / eventChunk.length, + type, + fromBlock: chunk2[0].fromBlock, + toBlock: chunk2[chunk2.length - 1].toBlock, + count: fetchedEvents.length + }); + } + } + return events; + }); + } +} + +var __defProp$3 = Object.defineProperty; +var __defProps$2 = Object.defineProperties; +var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp$3 = Object.prototype.hasOwnProperty; +var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$3 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + if (__getOwnPropSymbols$3) + for (var prop of __getOwnPropSymbols$3(b)) { + if (__propIsEnum$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async$a = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const DEPOSIT = "deposit"; +const WITHDRAWAL = "withdrawal"; +class BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + contract, + type = "", + deployedBlock = 0, + fetchDataOptions: fetchDataOptions2 + }) { + this.netId = netId; + this.provider = provider; + this.graphApi = graphApi; + this.subgraphName = subgraphName; + this.fetchDataOptions = fetchDataOptions2; + this.contract = contract; + this.type = type; + this.deployedBlock = deployedBlock; + this.batchEventsService = new BatchEventsService({ + provider, + contract, + onProgress: this.updateEventProgress + }); + } + getInstanceName() { + return ""; + } + getType() { + return this.type || ""; + } + getGraphMethod() { + return ""; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { + } + updateBlockProgress({ percentage, currentIndex, totalIndex }) { + } + updateTransactionProgress({ percentage, currentIndex, totalIndex }) { + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + formatEvents(events) { + return __async$a(this, null, function* () { + return yield new Promise((resolve) => resolve(events)); + }); + } + /** + * Get saved or cached events + */ + getEventsFromDB() { + return __async$a(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getEventsFromCache() { + return __async$a(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getSavedEvents() { + return __async$a(this, null, function* () { + let cachedEvents = yield this.getEventsFromDB(); + if (!cachedEvents || !cachedEvents.events.length) { + cachedEvents = yield this.getEventsFromCache(); + } + return cachedEvents; + }); + } + /** + * Get latest events + */ + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ + fromBlock, + methodName = "" + }) { + if (!this.graphApi || !this.subgraphName) { + return { + events: [], + lastBlock: fromBlock + }; + } + const { events, lastSyncBlock } = yield graph[methodName || this.getGraphMethod()](__spreadValues$3({ + fromBlock + }, this.getGraphParams())); + return { + events, + lastBlock: lastSyncBlock + }; + }); + } + getEventsFromRpc(_0) { + return __async$a(this, arguments, function* ({ + fromBlock, + toBlock + }) { + try { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + if (fromBlock >= toBlock) { + return { + events: [], + lastBlock: toBlock + }; + } + this.updateEventProgress({ percentage: 0, type: this.getType() }); + const events = yield this.formatEvents( + yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) + ); + if (!events.length) { + return { + events, + lastBlock: toBlock + }; + } + return { + events, + lastBlock: toBlock + }; + } catch (err) { + console.log(err); + return { + events: [], + lastBlock: fromBlock + }; + } + }); + } + getLatestEvents(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + const allEvents = []; + const graphEvents = yield this.getEventsFromGraph({ fromBlock }); + const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; + const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); + allEvents.push(...graphEvents.events); + allEvents.push(...rpcEvents.events); + const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; + return { + events: allEvents, + lastBlock + }; + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validateEvents({ events, lastBlock }) { + } + /** + * Handle saving events + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + saveEvents(_0) { + return __async$a(this, arguments, function* ({ events, lastBlock }) { + }); + } + /** + * Trigger saving and receiving latest events + */ + updateEvents() { + return __async$a(this, null, function* () { + const savedEvents = yield this.getSavedEvents(); + let fromBlock = this.deployedBlock; + if (savedEvents && savedEvents.lastBlock) { + fromBlock = savedEvents.lastBlock + 1; + } + const newEvents = yield this.getLatestEvents({ fromBlock }); + const eventSet = /* @__PURE__ */ new Set(); + let allEvents = []; + allEvents.push(...savedEvents.events); + allEvents.push(...newEvents.events); + allEvents = allEvents.sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }).filter(({ transactionHash, logIndex }) => { + const eventKey = `${transactionHash}_${logIndex}`; + const hasEvent = eventSet.has(eventKey); + eventSet.add(eventKey); + return !hasEvent; + }); + const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; + this.validateEvents({ events: allEvents, lastBlock }); + yield this.saveEvents({ events: allEvents, lastBlock }); + return { + events: allEvents, + lastBlock + }; + }); + } +} +class BaseDepositsService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.amount = amount; + this.currency = currency; + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + this.batchBlockService = new BatchBlockService({ + provider, + onProgress: this.updateBlockProgress + }); + } + getInstanceName() { + return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; + } + getGraphMethod() { + return `getAll${this.getType()}s`; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + amount: this.amount, + currency: this.currency, + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + formatEvents(events) { + return __async$a(this, null, function* () { + const type = this.getType().toLowerCase(); + if (type === DEPOSIT) { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { commitment, leafIndex, timestamp } = args; + return { + blockNumber, + logIndex, + transactionHash, + commitment, + leafIndex: Number(leafIndex), + timestamp: Number(timestamp) + }; + }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) + ]); + return formattedEvents.map((event) => { + const { from } = txs.find(({ hash }) => hash === event.transactionHash); + return __spreadProps$2(__spreadValues$3({}, event), { + from + }); + }); + } else { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { nullifierHash, to, fee } = args; + return { + blockNumber, + logIndex, + transactionHash, + nullifierHash: String(nullifierHash), + to: getAddress(to), + fee: String(fee) + }; + }); + const blocks = yield this.batchBlockService.getBatchBlocks([ + ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) + ]); + return formattedEvents.map((event) => { + const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); + return __spreadProps$2(__spreadValues$3({}, event), { + timestamp + }); + }); + } + }); + } + validateEvents({ events }) { + if (events.length && this.getType().toLowerCase() === DEPOSIT) { + const lastEvent = events[events.length - 1]; + if (lastEvent.leafIndex !== events.length - 1) { + const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; + throw new Error(errMsg); + } + } + } +} +class BaseEchoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `echo_${this.netId}`; + } + getType() { + return "Echo"; + } + getGraphMethod() { + return "getAllGraphEchoEvents"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { who, data } = args; + if (who && data) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + address: who, + encryptedAccount: data + }); + } + }).filter((e) => e); + }); + } + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseEncryptedNotesService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `encrypted_notes_${this.netId}`; + } + getType() { + return "EncryptedNote"; + } + getGraphMethod() { + return "getAllEncryptedNotes"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { encryptedNote } = args; + if (encryptedNote) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + encryptedNote + }); + } + }).filter((e) => e); + }); + } +} +class BaseGovernanceService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.batchTransactionService = new BatchTransactionService({ + provider, + onProgress: this.updateTransactionProgress + }); + } + getInstanceName() { + return `governance_${this.netId}`; + } + getType() { + return "*"; + } + getGraphMethod() { + return "getAllGovernanceEvents"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + const proposalEvents = []; + const votedEvents = []; + const delegatedEvents = []; + const undelegatedEvents = []; + events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash, + event + }; + if (event === "ProposalCreated") { + const { id, proposer, target, startTime, endTime, description } = args; + proposalEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + id: Number(id), + proposer, + target, + startTime: Number(startTime), + endTime: Number(endTime), + description + })); + } + if (event === "Voted") { + const { proposalId, voter, support, votes } = args; + votedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + proposalId: Number(proposalId), + voter, + support, + votes, + from: "", + input: "" + })); + } + if (event === "Delegated") { + const { account, to: delegateTo } = args; + delegatedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + account, + delegateTo + })); + } + if (event === "Undelegated") { + const { account, from: delegateFrom } = args; + undelegatedEvents.push(__spreadProps$2(__spreadValues$3({}, eventObjects), { + account, + delegateFrom + })); + } + }); + if (votedEvents.length) { + this.updateTransactionProgress({ percentage: 0 }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) + ]); + votedEvents.forEach((event, index) => { + let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); + if (!input || input.length > 2048) { + input = ""; + } + votedEvents[index].from = from; + votedEvents[index].input = input; + }); + } + return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; + }); + } + getEventsFromGraph(_0) { + return __async$a(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseRegistryService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `registered_${this.netId}`; + } + // Name of type used for events + getType() { + return "RelayerRegistered"; + } + // Name of method used for graph + getGraphMethod() { + return "getAllRegisters"; + } + formatEvents(events) { + return __async$a(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps$2(__spreadValues$3({}, eventObjects), { + ensName: args.ensName, + relayerAddress: args.relayerAddress + }); + }); + }); + } + fetchRelayers() { + return __async$a(this, null, function* () { + return (yield this.updateEvents()).events; + }); + } +} + +var __async$9 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function existsAsync(fileOrDir) { + return __async$9(this, null, function* () { + try { + yield stat(fileOrDir); + return true; + } catch (e) { + return false; + } + }); +} +function zipAsync(file) { + return new Promise((res, rej) => { + zip(file, { mtime: /* @__PURE__ */ new Date("1/1/1980") }, (err, data) => { + if (err) { + rej(err); + return; + } + res(data); + }); + }); +} +function unzipAsync(data) { + return new Promise((res, rej) => { + unzip(data, {}, (err, data2) => { + if (err) { + rej(err); + return; + } + res(data2); + }); + }); +} +function saveUserFile(_0) { + return __async$9(this, arguments, function* ({ + fileName, + userDirectory, + dataString + }) { + fileName = fileName.toLowerCase(); + const filePath = path.join(userDirectory, fileName); + const payload = yield zipAsync({ + [fileName]: new TextEncoder().encode(dataString) + }); + if (!(yield existsAsync(userDirectory))) { + yield mkdir(userDirectory, { recursive: true }); + } + yield writeFile(filePath + ".zip", payload); + yield writeFile(filePath, dataString); + }); +} +function loadSavedEvents(_0) { + return __async$9(this, arguments, function* ({ + name, + userDirectory, + deployedBlock + }) { + const filePath = path.join(userDirectory, `${name}.json`.toLowerCase()); + if (!(yield existsAsync(filePath))) { + return { + events: [], + lastBlock: null + }; + } + try { + const events = JSON.parse(yield readFile(filePath, { encoding: "utf8" })); + return { + events, + lastBlock: events && events.length ? events[events.length - 1].blockNumber : deployedBlock + }; + } catch (err) { + console.log("Method loadSavedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} +function download(_0) { + return __async$9(this, arguments, function* ({ name, cacheDirectory }) { + const fileName = `${name}.json`.toLowerCase(); + const zipName = `${fileName}.zip`; + const zipPath = path.join(cacheDirectory, zipName); + const data = yield readFile(zipPath); + const { [fileName]: content } = yield unzipAsync(data); + return new TextDecoder().decode(content); + }); +} +function loadCachedEvents(_0) { + return __async$9(this, arguments, function* ({ + name, + cacheDirectory, + deployedBlock + }) { + try { + const module = yield download({ cacheDirectory, name }); + if (module) { + const events = JSON.parse(module); + const lastBlock = events && events.length ? events[events.length - 1].blockNumber : deployedBlock; + return { + events, + lastBlock + }; + } + return { + events: [], + lastBlock: deployedBlock + }; + } catch (err) { + console.log("Method loadCachedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} + +var __async$8 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class NodeDepositsService extends BaseDepositsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} deposit txs of ${totalIndex}`); + } + } + updateBlockProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} withdrawal blocks of ${totalIndex}`); + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log( + "Updating events for", + this.amount, + this.currency.toUpperCase(), + `${this.getType().toLowerCase()}s +` + ); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log("Updating events for", this.amount, this.currency.toUpperCase(), `${this.getType().toLowerCase()}s +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: `${this.getType()}s`, hAlign: "center" }], + ["Instance", `${this.netId} chain ${this.amount} ${this.currency.toUpperCase()}`], + ["Anonymity set", `${events.length} equal user ${this.getType().toLowerCase()}s`], + [{ colSpan: 2, content: `Latest ${this.getType().toLowerCase()}s` }], + ...events.slice(events.length - 10).reverse().map(({ timestamp }, index) => { + const eventIndex = events.length - index; + const eventTime = moment.unix(timestamp).fromNow(); + return [eventIndex, eventTime]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEchoService extends BaseEchoService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Echo Accounts", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEncryptedNotesService extends BaseEncryptedNotesService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Encrypted Notes", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeGovernanceService extends BaseGovernanceService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} governance txs of ${totalIndex}`); + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Governance Events", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeRegistryService extends BaseRegistryService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async$8(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield loadSavedEvents({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async$8(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield loadCachedEvents({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async$8(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new Table(); + eventTable.push( + [{ colSpan: 2, content: "Registered Relayers", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield saveUserFile({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} + +var __defProp$2 = Object.defineProperty; +var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; +var __hasOwnProp$2 = Object.prototype.hasOwnProperty; +var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$2 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + if (__getOwnPropSymbols$2) + for (var prop of __getOwnPropSymbols$2(b)) { + if (__propIsEnum$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + } + return a; +}; +var NetId = /* @__PURE__ */ ((NetId2) => { + NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; + NetId2[NetId2["BSC"] = 56] = "BSC"; + NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; + NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; + NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; + NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; + NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; + NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + return NetId2; +})(NetId || {}); +const theGraph = { + name: "Hosted Graph", + url: "https://api.thegraph.com" +}; +const tornado = { + name: "Tornado Subgraphs", + url: "https://tornadocash-rpc.com" +}; +const defaultConfig = { + [1 /* MAINNET */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 80, + fast: 50, + standard: 25, + low: 8 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Mainnet", + deployedBlock: 9116966, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + mevblockerRPC: { + name: "MevblockerRPC", + url: "https://rpc.mevblocker.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/ethereum-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://eth-mainnet.nodereal.io/v1/1659dfb40aa24bbb8153a677b98064d7" + }, + notadegenRPC: { + name: "NotADegen RPC", + url: "https://rpc.notadegen.com/eth" + }, + keydonixRPC: { + name: "Keydonix RPC", + url: "https://ethereum.keydonix.com/v1/mainnet" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/eth" + } + }, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", + echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", + governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", + stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", + registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", + aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", + reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", + tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", + registrySubgraph: "tornadocash/tornado-relayer-registry", + governanceSubgraph: "tornadocash/tornado-governance", + subgraphs: { + tornado, + theGraph + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", + "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", + "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", + "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", + "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", + "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", + "100000": "0x23773E65ed146A459791799d01336DB287f25334" + }, + tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + }, + cdai: { + instanceAddress: { + "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", + "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", + "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", + "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" + }, + tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", + tokenGasLimit: 2e5, + symbol: "cDAI", + decimals: 8, + gasLimit: 7e5 + }, + usdc: { + instanceAddress: { + "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", + "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" + }, + tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + tokenGasLimit: 7e4, + symbol: "USDC", + decimals: 6, + gasLimit: 7e5 + }, + usdt: { + instanceAddress: { + "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", + "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" + }, + tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + tokenGasLimit: 7e4, + symbol: "USDT", + decimals: 6, + gasLimit: 7e5 + }, + wbtc: { + instanceAddress: { + "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", + "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", + "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" + }, + tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", + tokenGasLimit: 7e4, + symbol: "WBTC", + decimals: 8, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "mainnet-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 11474695, + NOTE_ACCOUNT_BLOCK: 11842486, + ENCRYPTED_NOTES_BLOCK: 12143762, + REGISTRY_BLOCK: 14173129, + MINING_BLOCK_TIME: 15 + } + }, + [56 /* BSC */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 5, + fast: 5, + standard: 5, + low: 5 + }, + nativeCurrency: "bnb", + currencyName: "BNB", + explorerUrl: "https://bscscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Binance Smart Chain", + deployedBlock: 8158799, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/bsc" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://bsc-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/bsc-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/bnb" + } + }, + tokens: { + bnb: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "BNB", + decimals: 18 + } + }, + ensSubdomainKey: "bsc-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 8159269, + ENCRYPTED_NOTES_BLOCK: 8159269 + } + }, + [137 /* POLYGON */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 100, + fast: 75, + standard: 50, + low: 30 + }, + nativeCurrency: "matic", + currencyName: "MATIC", + explorerUrl: "https://polygonscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Polygon (Matic) Network", + deployedBlock: 16257962, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", + tornadoSubgraph: "tornadocash/matic-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + chainnodes: { + name: "Tornado RPC", + url: "https://polygon-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/polygon-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/matic" + } + }, + tokens: { + matic: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "MATIC", + decimals: 18 + } + }, + ensSubdomainKey: "polygon-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 16257996, + ENCRYPTED_NOTES_BLOCK: 16257996 + } + }, + [10 /* OPTIMISM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 1e-3, + fast: 1e-3, + standard: 1e-3, + low: 1e-3 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://optimistic.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Optimism", + deployedBlock: 2243689, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", + tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/op" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://optimism-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + optimism: { + name: "Optimism RPC", + url: "https://mainnet.optimism.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/optimism-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/op" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "optimism-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 2243694, + ENCRYPTED_NOTES_BLOCK: 2243694 + } + }, + [42161 /* ARBITRUM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 4, + fast: 3, + standard: 2.52, + low: 2.29 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://arbiscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Arbitrum One", + deployedBlock: 3430648, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/arbitrum" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://arbitrum-one.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + arbitrum: { + name: "Arbitrum RPC", + url: "https://arb1.arbitrum.io/rpc" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + oneRpc: { + name: "1rpc", + url: "https://1rpc.io/arb" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "arbitrum-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 3430605, + ENCRYPTED_NOTES_BLOCK: 3430605 + } + }, + [100 /* GNOSIS */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 6, + fast: 5, + standard: 4, + low: 1 + }, + nativeCurrency: "xdai", + currencyName: "xDAI", + explorerUrl: "https://gnosisscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Gnosis Chain", + deployedBlock: 17754561, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/gnosis" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://gnosis-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + gnosis: { + name: "Gnosis RPC", + url: "https://rpc.gnosischain.com" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + blockPi: { + name: "BlockPi", + url: "https://gnosis.blockpi.network/v1/rpc/public" + } + }, + tokens: { + xdai: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "xDAI", + decimals: 18 + } + }, + ensSubdomainKey: "gnosis-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 17754564, + ENCRYPTED_NOTES_BLOCK: 17754564 + } + }, + [43114 /* AVALANCHE */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 225, + fast: 35, + standard: 25, + low: 25 + }, + nativeCurrency: "avax", + currencyName: "AVAX", + explorerUrl: "https://snowtrace.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Avalanche Mainnet", + deployedBlock: 4429818, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", + subgraphs: { + theGraph + }, + rpcUrls: { + oneRPC: { + name: "OneRPC", + url: "https://1rpc.io/avax/c" + }, + avalancheRPC: { + name: "Avalanche RPC", + url: "https://api.avax.network/ext/bc/C/rpc" + }, + meowRPC: { + name: "Meow RPC", + url: "https://avax.meowrpc.com" + } + }, + tokens: { + avax: { + instanceAddress: { + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" + }, + symbol: "AVAX", + decimals: 18 + } + }, + ensSubdomainKey: "avalanche-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 4429813, + ENCRYPTED_NOTES_BLOCK: 4429813 + } + }, + [11155111 /* SEPOLIA */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 2, + fast: 2, + standard: 2, + low: 2 + }, + nativeCurrency: "eth", + currencyName: "SepoliaETH", + explorerUrl: "https://sepolia.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Sepolia", + deployedBlock: 5594395, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", + governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", + stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", + registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", + aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", + reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", + tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", + subgraphs: { + tornado + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/sepolia" + }, + sepolia: { + name: "Sepolia RPC", + url: "https://rpc.sepolia.org" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://sepolia.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", + "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", + "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", + "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", + "1000": "0x50a637770F5d161999420F7d70d888DE47207145", + "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", + "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" + }, + tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "sepolia-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 5594395, + NOTE_ACCOUNT_BLOCK: 5594395, + ENCRYPTED_NOTES_BLOCK: 5594395, + MINING_BLOCK_TIME: 15 + } + } +}; +const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); +let customConfig = {}; +function addNetwork(newConfig) { + enabledChains.push( + ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) + ); + customConfig = __spreadValues$2(__spreadValues$2({}, customConfig), newConfig); +} +function getNetworkConfig() { + const allConfig = __spreadValues$2(__spreadValues$2({}, defaultConfig), customConfig); + return enabledChains.reduce((acc, curr) => { + acc[curr] = allConfig[curr]; + return acc; + }, {}); +} +function getConfig(netId) { + const allConfig = getNetworkConfig(); + const chainConfig = allConfig[netId]; + if (!chainConfig) { + const errMsg = `No config found for network ${netId}!`; + throw new Error(errMsg); + } + return chainConfig; +} +function getInstanceByAddress({ netId, address }) { + const { tokens } = getConfig(netId); + for (const [currency, { instanceAddress }] of Object.entries(tokens)) { + for (const [amount, instance] of Object.entries(instanceAddress)) { + if (instance === address) { + return { + amount, + currency + }; + } + } + } +} +function getSubdomains() { + const allConfig = getNetworkConfig(); + return enabledChains.map((chain) => allConfig[chain].ensSubdomainKey); +} + +const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; +const bnType = { type: "string", BN: true }; +const statusSchema = { + type: "object", + properties: { + rewardAccount: addressType, + gasPrices: { + type: "object", + properties: { + fast: { type: "number" }, + additionalProperties: { type: "number" } + }, + required: ["fast"] + }, + netId: { type: "integer" }, + tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, + latestBlock: { type: "number" }, + version: { type: "string" }, + health: { + type: "object", + properties: { + status: { const: "true" }, + error: { type: "string" } + }, + required: ["status"] + }, + currentQueue: { type: "number" } + }, + required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] +}; +function getStatusSchema(netId, config) { + const { tokens, optionalTokens = [], nativeCurrency } = config; + const schema = JSON.parse(JSON.stringify(statusSchema)); + const instances = Object.keys(tokens).reduce( + (acc, token) => { + const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; + const amounts = Object.keys(instanceAddress); + const instanceProperties = { + type: "object", + properties: { + instanceAddress: { + type: "object", + properties: amounts.reduce((acc2, cur) => { + acc2[cur] = addressType; + return acc2; + }, {}), + required: amounts.filter((amount) => !optionalInstances.includes(amount)) + }, + decimals: { enum: [decimals] } + }, + required: ["instanceAddress", "decimals"].concat( + tokenAddress ? ["tokenAddress"] : [], + symbol ? ["symbol"] : [] + ) + }; + if (tokenAddress) { + instanceProperties.properties.tokenAddress = addressType; + } + if (symbol) { + instanceProperties.properties.symbol = { enum: [symbol] }; + } + acc.properties[token] = instanceProperties; + if (!optionalTokens.includes(token)) { + acc.required.push(token); + } + return acc; + }, + { + type: "object", + properties: {}, + required: [] + } + ); + schema.properties.instances = instances; + if (netId === NetId.MAINNET) { + const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); + const ethPrices = { + type: "object", + properties: _tokens.reduce((acc, token) => { + acc[token] = bnType; + return acc; + }, {}) + // required: _tokens + }; + schema.properties.ethPrices = ethPrices; + } + return schema; +} + +const jobsSchema = { + type: "object", + properties: { + error: { type: "string" }, + id: { type: "string" }, + type: { type: "string" }, + status: { type: "string" }, + contract: { type: "string" }, + proof: { type: "string" }, + args: { + type: "array", + items: { type: "string" } + }, + txHash: { type: "string" }, + confirmations: { type: "number" }, + failedReason: { type: "string" } + }, + required: ["id", "status"] +}; + +const ajv = new Ajv({ allErrors: true }); +ajv.addKeyword({ + keyword: "BN", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validate: (schema, data) => { + try { + BigInt(data); + return true; + } catch (e) { + return false; + } + }, + errors: true +}); + +var __async$7 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class Pedersen { + constructor() { + this.pedersenPromise = this.initPedersen(); + } + initPedersen() { + return __async$7(this, null, function* () { + this.pedersenHash = yield buildPedersenHash(); + this.babyJub = this.pedersenHash.babyJub; + }); + } + unpackPoint(buffer) { + return __async$7(this, null, function* () { + var _a, _b; + yield this.pedersenPromise; + return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); + }); + } + toStringBuffer(buffer) { + var _a; + return (_a = this.babyJub) == null ? void 0 : _a.F.toString(buffer); + } +} +const pedersen = new Pedersen(); +function buffPedersenHash(buffer) { + return __async$7(this, null, function* () { + const [hash] = yield pedersen.unpackPoint(buffer); + return pedersen.toStringBuffer(hash); + }); +} + +var __async$6 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function createDeposit(_0) { + return __async$6(this, arguments, function* ({ nullifier, secret }) { + const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]); + const noteHex = toFixedHex(bytesToBN(preimage), 62); + const commitment = BigInt(yield buffPedersenHash(preimage)); + const commitmentHex = toFixedHex(commitment); + const nullifierHash = BigInt(yield buffPedersenHash(leInt2Buff(nullifier))); + const nullifierHex = toFixedHex(nullifierHash); + return { + preimage, + noteHex, + commitment, + commitmentHex, + nullifierHash, + nullifierHex + }; + }); +} +class Deposit { + constructor({ + currency, + amount, + netId, + nullifier, + secret, + note, + noteHex, + invoice, + commitmentHex, + nullifierHex + }) { + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.nullifier = nullifier; + this.secret = secret; + this.note = note; + this.noteHex = noteHex; + this.invoice = invoice; + this.commitmentHex = commitmentHex; + this.nullifierHex = nullifierHex; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + nullifier: this.nullifier, + secret: this.secret, + note: this.note, + noteHex: this.noteHex, + invoice: this.invoice, + commitmentHex: this.commitmentHex, + nullifierHex: this.nullifierHex + }, + null, + 2 + ); + } + static createNote(_0) { + return __async$6(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { + if (!nullifier) { + nullifier = rBigInt(31); + } + if (!secret) { + secret = rBigInt(31); + } + const depositObject = yield createDeposit({ + nullifier, + secret + }); + const newDeposit = new Deposit({ + currency: currency.toLowerCase(), + amount, + netId, + note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`, + noteHex: depositObject.noteHex, + invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } + static parseNote(noteString) { + return __async$6(this, null, function* () { + const noteRegex = new RegExp("tornado-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{124})", "g"); + const match = noteRegex.exec(noteString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + const bytes = bnToBytes("0x" + matchGroup.note); + const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString()); + const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString()); + const depositObject = yield createDeposit({ nullifier, secret }); + const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`; + const newDeposit = new Deposit({ + currency, + amount, + netId, + note: noteString, + noteHex: depositObject.noteHex, + invoice, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } +} +class Invoice { + constructor(invoiceString) { + const invoiceRegex = new RegExp("tornadoInvoice-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{64})", "g"); + const match = invoiceRegex.exec(invoiceString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.commitment = "0x" + matchGroup.commitment; + this.invoice = invoiceString; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + commitment: this.commitment, + invoice: this.invoice + }, + null, + 2 + ); + } +} + +function packEncryptedMessage({ nonce, ephemPublicKey, ciphertext }) { + const nonceBuf = toFixedHex(bytesToHex(base64ToBytes(nonce)), 24); + const ephemPublicKeyBuf = toFixedHex(bytesToHex(base64ToBytes(ephemPublicKey)), 32); + const ciphertextBuf = bytesToHex(base64ToBytes(ciphertext)); + const messageBuff = concatBytes(hexToBytes(nonceBuf), hexToBytes(ephemPublicKeyBuf), hexToBytes(ciphertextBuf)); + return bytesToHex(messageBuff); +} +function unpackEncryptedMessage(encryptedMessage) { + const messageBuff = hexToBytes(encryptedMessage); + const nonceBuf = bytesToBase64(messageBuff.slice(0, 24)); + const ephemPublicKeyBuf = bytesToBase64(messageBuff.slice(24, 56)); + const ciphertextBuf = bytesToBase64(messageBuff.slice(56)); + return { + messageBuff: bytesToHex(messageBuff), + version: "x25519-xsalsa20-poly1305", + nonce: nonceBuf, + ephemPublicKey: ephemPublicKeyBuf, + ciphertext: ciphertextBuf + }; +} +class NoteAccount { + constructor({ netId, blockNumber, recoveryKey, Echoer: Echoer2 }) { + if (!recoveryKey) { + recoveryKey = bytesToHex(crypto.getRandomValues(new Uint8Array(32))).slice(2); + } + this.netId = Math.floor(Number(netId)); + this.blockNumber = blockNumber; + this.recoveryKey = recoveryKey; + this.recoveryAddress = computeAddress("0x" + recoveryKey); + this.recoveryPublicKey = getEncryptionPublicKey(recoveryKey); + this.Echoer = Echoer2; + } + /** + * Intends to mock eth_getEncryptionPublicKey behavior from MetaMask + * In order to make the recoveryKey retrival from Echoer possible from the bare private key + */ + static getWalletPublicKey(wallet) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + return getEncryptionPublicKey(privateKey); + } + // This function intends to provide an encrypted value of recoveryKey for an on-chain Echoer backup purpose + // Thus, the pubKey should be derived by a Wallet instance or from Web3 wallets + // pubKey: base64 encoded 32 bytes key from https://docs.metamask.io/wallet/reference/eth_getencryptionpublickey/ + getEncryptedAccount(walletPublicKey) { + const encryptedData = encrypt({ + publicKey: walletPublicKey, + data: this.recoveryKey, + version: "x25519-xsalsa20-poly1305" + }); + const data = packEncryptedMessage(encryptedData); + return { + // Use this later to save hexPrivateKey generated with + // Buffer.from(JSON.stringify(encryptedData)).toString('hex') + // As we don't use buffer with this library we should leave UI to do the rest + encryptedData, + // Data that could be used as an echo(data) params + data + }; + } + /** + * Decrypt Echoer backuped note encryption account with private keys + */ + decryptAccountsWithWallet(wallet, events) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedAccount); + const recoveryKey = decrypt({ + encryptedData: unpackedMessage, + privateKey + }); + decryptedEvents.push( + new NoteAccount({ + netId: this.netId, + blockNumber: event.blockNumber, + recoveryKey, + Echoer: this.Echoer + }) + ); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + decryptNotes(events) { + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedNote); + const [address, noteHex] = decrypt({ + encryptedData: unpackedMessage, + privateKey: this.recoveryKey + }).split("-"); + decryptedEvents.push({ + blockNumber: event.blockNumber, + address: getAddress(address), + noteHex + }); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + encryptNote({ address, noteHex }) { + const encryptedData = encrypt({ + publicKey: this.recoveryPublicKey, + data: `${address}-${noteHex}`, + version: "x25519-xsalsa20-poly1305" + }); + return packEncryptedMessage(encryptedData); + } +} + +const DUMMY_ADDRESS = "0x1111111111111111111111111111111111111111"; +const DUMMY_NONCE = "0x1111111111111111111111111111111111111111111111111111111111111111"; +const DUMMY_WITHDRAW_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; +function convertETHToTokenAmount(amountInWei, tokenPriceInWei, tokenDecimals = 18) { + const tokenDecimalsMultiplier = BigInt(10 ** Number(tokenDecimals)); + return BigInt(amountInWei) * tokenDecimalsMultiplier / BigInt(tokenPriceInWei); +} +class TornadoFeeOracle { + constructor(ovmGasPriceOracle) { + if (ovmGasPriceOracle) { + this.ovmGasPriceOracle = ovmGasPriceOracle; + } + } + /** + * Calculate L1 fee for op-stack chains + * + * This is required since relayers would pay the full transaction fees for users + */ + fetchL1OptimismFee(tx) { + if (!this.ovmGasPriceOracle) { + return new Promise((resolve) => resolve(BigInt(0))); + } + if (!tx) { + tx = { + type: 0, + gasLimit: 1e6, + nonce: Number(DUMMY_NONCE), + data: DUMMY_WITHDRAW_DATA, + gasPrice: parseUnits("1", "gwei"), + from: DUMMY_ADDRESS, + to: DUMMY_ADDRESS + }; + } + return this.ovmGasPriceOracle.getL1Fee.staticCall(Transaction.from(tx).unsignedSerialized); + } + /** + * We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal + * So we default with 1M gas which is enough for two or three swaps + * Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI + */ + defaultEthRefund(gasPrice, gasLimit) { + return (gasPrice ? BigInt(gasPrice) : parseUnits("30", "gwei")) * BigInt(gasLimit || 1e6); + } + /** + * Calculates token amount for required ethRefund purchases required to calculate fees + */ + calculateTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals) { + return convertETHToTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals); + } + /** + * Warning: For tokens you need to check if the fees are above denomination + * (Usually happens for small denomination pool or if the gas price is high) + */ + calculateRelayerFee({ + gasPrice, + gasLimit = 6e5, + l1Fee = 0, + denomination, + ethRefund = BigInt(0), + tokenPriceInWei, + tokenDecimals = 18, + relayerFeePercent = 0.33, + isEth = true, + premiumPercent = 20 + }) { + const gasCosts = BigInt(gasPrice) * BigInt(gasLimit) + BigInt(l1Fee); + const relayerFee = BigInt(denomination) * BigInt(Math.floor(1e4 * relayerFeePercent)) / BigInt(1e4 * 100); + if (isEth) { + return (gasCosts + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } + const feeInEth = gasCosts + BigInt(ethRefund); + return (convertETHToTokenAmount(feeInEth, tokenPriceInWei, tokenDecimals) + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } +} + +var __async$5 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class Mimc { + constructor() { + this.mimcPromise = this.initMimc(); + } + initMimc() { + return __async$5(this, null, function* () { + this.sponge = yield buildMimcSponge(); + this.hash = (left, right) => { + var _a, _b; + return (_b = this.sponge) == null ? void 0 : _b.F.toString((_a = this.sponge) == null ? void 0 : _a.multiHash([BigInt(left), BigInt(right)])); + }; + }); + } + getHash() { + return __async$5(this, null, function* () { + yield this.mimcPromise; + return { + sponge: this.sponge, + hash: this.hash + }; + }); + } +} +const mimc = new Mimc(); + +var __async$4 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class MerkleTreeService { + constructor({ + netId, + amount, + currency, + Tornado, + commitmentHex, + merkleTreeHeight = 20, + emptyElement = "21663839004416932945382355908790599225266501822907911457504978515578255421292", + merkleWorkerPath + }) { + const instanceName = `${netId}_${currency}_${amount}`; + this.currency = currency; + this.amount = amount; + this.netId = Number(netId); + this.Tornado = Tornado; + this.instanceName = instanceName; + this.commitmentHex = commitmentHex; + this.merkleTreeHeight = merkleTreeHeight; + this.emptyElement = emptyElement; + this.merkleWorkerPath = merkleWorkerPath; + } + createTree(events) { + return __async$4(this, null, function* () { + const { hash: hashFunction } = yield mimc.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (isNode) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker$1(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + }); + }); + return MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new MerkleTree(this.merkleTreeHeight, events, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + createPartialTree(_0) { + return __async$4(this, arguments, function* ({ edge, elements }) { + const { hash: hashFunction } = yield mimc.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (isNode) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker$1(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + }); + }); + return PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new PartialMerkleTree(this.merkleTreeHeight, edge, elements, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + verifyTree(events) { + return __async$4(this, null, function* () { + console.log( + ` +Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while +` + ); + console.time("Created tree in"); + const tree = yield this.createTree(events.map(({ commitment }) => commitment)); + console.timeEnd("Created tree in"); + console.log(""); + const isKnownRoot = yield this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root))); + if (!isKnownRoot) { + const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; + throw new Error(errMsg); + } + return tree; + }); + } +} + +function parseNumber(value) { + if (!value || isNaN(Number(value))) { + throw new InvalidArgumentError("Invalid Number"); + } + return Number(value); +} +function parseUrl(value) { + if (!value || !validateUrl(value, ["http:", "https:"])) { + throw new InvalidArgumentError("Invalid URL"); + } + return value; +} +function parseRelayer(value) { + if (!value || !(value.endsWith(".eth") || validateUrl(value, ["http:", "https:"]))) { + throw new InvalidArgumentError("Invalid Relayer ETH address or URL"); + } + return value; +} +function parseAddress(value) { + if (!value) { + throw new InvalidArgumentError("Invalid Address"); + } + try { + return getAddress(value); + } catch (e) { + throw new InvalidArgumentError("Invalid Address"); + } +} +function parseMnemonic(value) { + if (!value) { + throw new InvalidArgumentError("Invalid Mnemonic"); + } + try { + Mnemonic.fromPhrase(value); + } catch (e) { + throw new InvalidArgumentError("Invalid Mnemonic"); + } + return value; +} +function parseKey(value) { + if (!value) { + throw new InvalidArgumentError("Invalid Private Key"); + } + if (value.length === 64) { + value = "0x" + value; + } + try { + computeAddress(value); + } catch (e) { + throw new InvalidArgumentError("Invalid Private Key"); + } + return value; +} +function parseRecoveryKey(value) { + if (!value) { + throw new InvalidArgumentError("Invalid Recovery Key"); + } + try { + computeAddress("0x" + value); + } catch (e) { + throw new InvalidArgumentError("Invalid Recovery Key"); + } + return value; +} + +class TokenPriceOracle { + constructor(provider, multicall2, oracle) { + this.provider = provider; + this.multicall = multicall2; + this.oracle = oracle; + } + fetchPrices(tokens) { + if (!this.oracle) { + return new Promise((resolve) => resolve(tokens.map(() => parseEther("0.0001")))); + } + return multicall( + this.multicall, + tokens.map((token) => ({ + contract: this.oracle, + name: "getRateToEth", + params: [token, true] + })) + ); + } +} + +var __defProp$1 = Object.defineProperty; +var __defProps$1 = Object.defineProperties; +var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; +var __hasOwnProp$1 = Object.prototype.hasOwnProperty; +var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$1 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + if (__getOwnPropSymbols$1) + for (var prop of __getOwnPropSymbols$1(b)) { + if (__propIsEnum$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); +var __async$3 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +const MIN_STAKE_BALANCE = parseEther("500"); +const semVerRegex = new RegExp("^(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)(?:-(?(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); +function parseSemanticVersion(version) { + const { groups } = semVerRegex.exec(version); + return groups; +} +function isRelayerUpdated(relayerVersion, netId) { + const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); + const requiredMajor = netId === NetId.MAINNET ? "4" : "5"; + const isUpdatedMajor = major === requiredMajor; + if (prerelease) + return false; + return isUpdatedMajor && (Number(patch) >= 5 || netId !== NetId.MAINNET); +} +function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { + if (tornadoServiceFee < minFee) { + tornadoServiceFee = minFee; + } else if (tornadoServiceFee >= maxFee) { + return BigInt(0); + } + const serviceFeeCoefficient = (tornadoServiceFee - minFee) ** 2; + const feeDiffCoefficient = 1 / (maxFee - minFee) ** 2; + const coefficientsMultiplier = 1 - feeDiffCoefficient * serviceFeeCoefficient; + return BigInt(Math.floor(Number(stakeBalance) * coefficientsMultiplier)); +} +function getWeightRandom(weightsScores, random) { + for (let i = 0; i < weightsScores.length; i++) { + if (random < weightsScores[i]) { + return i; + } + random = random - weightsScores[i]; + } + return Math.floor(Math.random() * weightsScores.length); +} +function getSupportedInstances(instanceList) { + const rawList = Object.values(instanceList).map(({ instanceAddress }) => { + return Object.values(instanceAddress); + }).flat(); + return rawList.map((l) => getAddress(l)); +} +function pickWeightedRandomRelayer(relayers, netId) { + let minFee, maxFee; + if (netId !== NetId.MAINNET) { + minFee = 0.01; + maxFee = 0.3; + } + const weightsScores = relayers.map((el) => calculateScore(el, minFee, maxFee)); + const totalWeight = weightsScores.reduce((acc, curr) => { + return acc = acc + curr; + }, BigInt("0")); + const random = BigInt(Number(totalWeight) * Math.random()); + const weightRandomIndex = getWeightRandom(weightsScores, random); + return relayers[weightRandomIndex]; +} +class RelayerClient { + constructor({ netId, config, Aggregator, fetchDataOptions: fetchDataOptions2 }) { + this.netId = netId; + this.config = config; + this.Aggregator = Aggregator; + this.fetchDataOptions = fetchDataOptions2; + } + askRelayerStatus(_0) { + return __async$3(this, arguments, function* ({ + hostname, + relayerAddress + }) { + var _a, _b; + const url = `https://${!hostname.endsWith("/") ? hostname + "/" : hostname}`; + const rawStatus = yield fetchData(`${url}status`, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + headers: { + "Content-Type": "application/json, application/x-www-form-urlencoded" + }, + timeout: ((_a = this.fetchDataOptions) == null ? void 0 : _a.torPort) ? 1e4 : 3e3, + maxRetry: ((_b = this.fetchDataOptions) == null ? void 0 : _b.torPort) ? 2 : 0 + })); + const statusValidator = ajv.compile(getStatusSchema(this.netId, this.config)); + if (!statusValidator(rawStatus)) { + throw new Error("Invalid status schema"); + } + const status = __spreadProps$1(__spreadValues$1({}, rawStatus), { + url + }); + if (status.currentQueue > 5) { + throw new Error("Withdrawal queue is overloaded"); + } + if (status.netId !== this.netId) { + throw new Error("This relayer serves a different network"); + } + if (relayerAddress && this.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) { + throw new Error("The Relayer reward address must match registered address"); + } + if (!isRelayerUpdated(status.version, this.netId)) { + throw new Error("Outdated version."); + } + return status; + }); + } + filterRelayer(curr, relayer, subdomains, debugRelayer = false) { + return __async$3(this, null, function* () { + var _a; + const { ensSubdomainKey } = this.config; + const subdomainIndex = subdomains.indexOf(ensSubdomainKey); + const mainnetSubdomain = curr.records[0]; + const hostname = curr.records[subdomainIndex]; + const isHostWithProtocol = hostname.includes("http"); + const { owner, balance: stakeBalance, isRegistered } = curr; + const { ensName, relayerAddress } = relayer; + const isOwner = !relayerAddress || relayerAddress === owner; + const hasMinBalance = stakeBalance >= MIN_STAKE_BALANCE; + const preCondition = hostname && isOwner && mainnetSubdomain && isRegistered && hasMinBalance && !isHostWithProtocol; + if (preCondition || debugRelayer) { + try { + const status = yield this.askRelayerStatus({ hostname, relayerAddress }); + return { + netId: status.netId, + url: status.url, + hostname, + ensName, + stakeBalance, + relayerAddress, + rewardAccount: getAddress(status.rewardAccount), + instances: getSupportedInstances(status.instances), + gasPrice: (_a = status.gasPrices) == null ? void 0 : _a.fast, + ethPrices: status.ethPrices, + currentQueue: status.currentQueue, + tornadoServiceFee: status.tornadoServiceFee + }; + } catch (err) { + if (debugRelayer) { + throw err; + } + return { + hostname, + relayerAddress, + errorMessage: err.message + }; + } + } else { + if (debugRelayer) { + const errMsg = `Relayer ${hostname} condition not met`; + throw new Error(errMsg); + } + return { + hostname, + relayerAddress, + errorMessage: `Relayer ${hostname} condition not met` + }; + } + }); + } + getValidRelayers(relayers, subdomains, debugRelayer = false) { + return __async$3(this, null, function* () { + const relayersSet = /* @__PURE__ */ new Set(); + const uniqueRelayers = relayers.reverse().filter(({ ensName }) => { + if (!relayersSet.has(ensName)) { + relayersSet.add(ensName); + return true; + } + return false; + }); + const relayerNameHashes = uniqueRelayers.map((r) => namehash(r.ensName)); + const relayersData = yield this.Aggregator.relayersData.staticCall(relayerNameHashes, subdomains); + const invalidRelayers = []; + const validRelayers = (yield Promise.all( + relayersData.map((curr, index) => this.filterRelayer(curr, uniqueRelayers[index], subdomains, debugRelayer)) + )).filter((r) => { + if (r.errorMessage) { + invalidRelayers.push(r); + return false; + } + return true; + }); + return { + validRelayers, + invalidRelayers + }; + }); + } + pickWeightedRandomRelayer(relayers) { + return pickWeightedRandomRelayer(relayers, this.netId); + } + tornadoWithdraw(_0) { + return __async$3(this, arguments, function* ({ contract, proof, args }) { + const { url } = this.selectedRelayer; + const withdrawResponse = yield fetchData(`${url}v1/tornadoWithdraw`, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + contract, + proof, + args + }) + })); + const { id, error } = withdrawResponse; + if (error) { + throw new Error(error); + } + let relayerStatus; + const jobUrl = `${url}v1/jobs/${id}`; + console.log(`Job submitted: ${jobUrl} +`); + while (!relayerStatus || !["FAILED", "CONFIRMED"].includes(relayerStatus)) { + const jobResponse = yield fetchData(jobUrl, __spreadProps$1(__spreadValues$1({}, this.fetchDataOptions), { + method: "GET", + headers: { + "Content-Type": "application/json" + } + })); + if (jobResponse.error) { + throw new Error(error); + } + const jobValidator = ajv.compile(jobsSchema); + if (!jobValidator(jobResponse)) { + const errMsg = `${jobUrl} has an invalid job response`; + throw new Error(errMsg); + } + const { status, txHash, confirmations, failedReason } = jobResponse; + if (relayerStatus !== status) { + if (status === "FAILED") { + const errMsg = `Job ${status}: ${jobUrl} failed reason: ${failedReason}`; + throw new Error(errMsg); + } else if (status === "SENT") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash} +`); + } else if (status === "MINED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else if (status === "CONFIRMED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else { + console.log(`Job ${status}: ${jobUrl} +`); + } + relayerStatus = status; + } + yield sleep(3e3); + } + }); + } +} + +var __async$2 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function getTokenBalances(_0) { + return __async$2(this, arguments, function* ({ + provider, + Multicall: Multicall2, + currencyName, + userAddress, + tokenAddresses = [] + }) { + const tokenCalls = tokenAddresses.map((tokenAddress) => { + const Token = ERC20__factory.connect(tokenAddress, provider); + return [ + { + contract: Token, + name: "balanceOf", + params: [userAddress] + }, + { + contract: Token, + name: "name" + }, + { + contract: Token, + name: "symbol" + }, + { + contract: Token, + name: "decimals" + } + ]; + }).flat(); + const multicallResults = yield multicall(Multicall2, [ + { + contract: Multicall2, + name: "getEthBalance", + params: [userAddress] + }, + ...tokenCalls.length ? tokenCalls : [] + ]); + const ethResults = multicallResults[0]; + const tokenResults = multicallResults.slice(1).length ? chunk(multicallResults.slice(1), tokenCalls.length / tokenAddresses.length) : []; + const tokenBalances = tokenResults.map((tokenResult, index) => { + const [tokenBalance, tokenName, tokenSymbol, tokenDecimals] = tokenResult; + const tokenAddress = tokenAddresses[index]; + return { + address: tokenAddress, + name: tokenName, + symbol: tokenSymbol, + decimals: Number(tokenDecimals), + balance: tokenBalance + }; + }); + return [ + { + address: ZeroAddress, + name: currencyName, + symbol: currencyName, + decimals: 18, + balance: ethResults + }, + ...tokenBalances + ]; + }); +} + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; +}; +var __async$1 = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class TreeCache { + constructor({ netId, amount, currency, userDirectory, PARTS_COUNT = 4 }) { + this.netId = netId; + this.amount = amount; + this.currency = currency; + this.userDirectory = userDirectory; + this.PARTS_COUNT = PARTS_COUNT; + } + getInstanceName() { + return `deposits_${this.netId}_${this.currency}_${this.amount}`; + } + createTree(events, tree) { + return __async$1(this, null, function* () { + const bloom = new BloomFilter(events.length); + console.log(`Creating cached tree for ${this.getInstanceName()} +`); + const eventsData = events.reduce( + (acc, _a, i) => { + var _b = _a, { leafIndex, commitment } = _b, rest = __objRest(_b, ["leafIndex", "commitment"]); + if (leafIndex !== i) { + throw new Error(`leafIndex (${leafIndex}) !== i (${i})`); + } + acc[commitment] = __spreadProps(__spreadValues({}, rest), { leafIndex }); + return acc; + }, + {} + ); + const slices = tree.getTreeSlices(this.PARTS_COUNT); + yield Promise.all( + slices.map((slice, index) => __async$1(this, null, function* () { + const metadata = slice.elements.reduce((acc, curr) => { + if (index < this.PARTS_COUNT - 1) { + bloom.add(curr); + } + acc.push(eventsData[curr]); + return acc; + }, []); + const dataString2 = JSON.stringify( + __spreadProps(__spreadValues({}, slice), { + metadata + }), + null, + 2 + ) + "\n"; + const fileName2 = `${this.getInstanceName()}_slice${index + 1}.json`; + yield saveUserFile({ + fileName: fileName2, + userDirectory: this.userDirectory, + dataString: dataString2 + }); + })) + ); + const dataString = bloom.serialize() + "\n"; + const fileName = `${this.getInstanceName()}_bloom.json`; + yield saveUserFile({ + fileName, + userDirectory: this.userDirectory, + dataString + }); + }); + } +} + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +let groth16; +const groth16Promise = (() => __async(void 0, null, function* () { + if (!groth16) { + groth16 = yield websnarkGroth({ wasmInitialMemory: 2e3 }); + } +}))(); +function calculateSnarkProof(input, circuit, provingKey) { + return __async(this, null, function* () { + yield groth16Promise; + const snarkInput = { + root: input.root, + nullifierHash: BigInt(input.nullifierHex).toString(), + recipient: BigInt(input.recipient), + relayer: BigInt(input.relayer), + fee: input.fee, + refund: input.refund, + nullifier: input.nullifier, + secret: input.secret, + pathElements: input.pathElements, + pathIndices: input.pathIndices + }; + console.log("Start generating SNARK proof", snarkInput); + console.time("SNARK proof time"); + const proofData = yield websnarkUtils.genWitnessAndProve(groth16, snarkInput, circuit, provingKey); + const proof = websnarkUtils.toSolidityInput(proofData).proof; + console.timeEnd("SNARK proof time"); + const args = [ + toFixedHex(input.root, 32), + toFixedHex(input.nullifierHex, 32), + input.recipient, + input.relayer, + toFixedHex(input.fee, 32), + toFixedHex(input.refund, 32) + ]; + return { proof, args }; + }); +} + +export { BaseDepositsService, BaseEchoService, BaseEncryptedNotesService, BaseEventsService, BaseGovernanceService, BaseRegistryService, BatchBlockService, BatchEventsService, BatchTransactionService, DEPOSIT, Deposit, ENS__factory, ERC20__factory, GET_DEPOSITS, GET_ECHO_EVENTS, GET_ENCRYPTED_NOTES, GET_GOVERNANCE_APY, GET_GOVERNANCE_EVENTS, GET_NOTE_ACCOUNTS, GET_REGISTERED, GET_STATISTIC, GET_WITHDRAWALS, GasPriceOracle__factory, Invoice, MIN_STAKE_BALANCE, MerkleTreeService, Mimc, Multicall__factory, NetId, NodeDepositsService, NodeEchoService, NodeEncryptedNotesService, NodeGovernanceService, NodeRegistryService, NoteAccount, OffchainOracle__factory, OvmGasPriceOracle__factory, Pedersen, RelayerClient, ReverseRecords__factory, TokenPriceOracle, TornadoBrowserProvider, TornadoFeeOracle, TornadoRpcSigner, TornadoVoidSigner, TornadoWallet, TreeCache, WITHDRAWAL, _META, addNetwork, ajv, base64ToBytes, bigIntReplacer, bnToBytes, buffPedersenHash, bufferToBytes, bytesToBN, bytesToBase64, bytesToHex, calculateScore, calculateSnarkProof, chunk, concatBytes, convertETHToTokenAmount, createDeposit, crypto, customConfig, defaultConfig, defaultUserAgent, download, enabledChains, existsAsync, index as factories, fetch, fetchData, fetchGetUrlFunc, getAllDeposits, getAllEncryptedNotes, getAllGovernanceEvents, getAllGraphEchoEvents, getAllRegisters, getAllWithdrawals, getConfig, getDeposits, getEncryptedNotes, getGasOraclePlugin, getGovernanceEvents, getGraphEchoEvents, getHttpAgent, getInstanceByAddress, getMeta, getNetworkConfig, getNoteAccounts, getProvider, getProviderWithNetId, getRegisters, getStatistic, getStatusSchema, getSubdomains, getSupportedInstances, getTokenBalances, getWeightRandom, getWithdrawals, hexToBytes, isNode, isRelayerUpdated, jobsSchema, leBuff2Int, leInt2Buff, loadCachedEvents, loadSavedEvents, mimc, multicall, packEncryptedMessage, parseAddress, parseKey, parseMnemonic, parseNumber, parseRecoveryKey, parseRelayer, parseSemanticVersion, parseUrl, pedersen, pickWeightedRandomRelayer, populateTransaction, queryGraph, rBigInt, saveUserFile, sleep, substring, toFixedHex, toFixedLength, unpackEncryptedMessage, unzipAsync, validateUrl, zipAsync }; diff --git a/dist/index.umd.js b/dist/index.umd.js new file mode 100644 index 0000000..860c3bb --- /dev/null +++ b/dist/index.umd.js @@ -0,0 +1,201479 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["Tornado"] = factory(); + else + root["Tornado"] = factory(); +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 66289: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RLP = exports.utils = exports.decode = exports.encode = void 0; +/** + * RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/ + * This function takes in data, converts it to Uint8Array if not, + * and adds a length for recursion. + * @param input Will be converted to Uint8Array + * @returns Uint8Array of encoded data + **/ +function encode(input) { + if (Array.isArray(input)) { + const output = []; + let outputLength = 0; + for (let i = 0; i < input.length; i++) { + const encoded = encode(input[i]); + output.push(encoded); + outputLength += encoded.length; + } + return concatBytes(encodeLength(outputLength, 192), ...output); + } + const inputBuf = toBytes(input); + if (inputBuf.length === 1 && inputBuf[0] < 128) { + return inputBuf; + } + return concatBytes(encodeLength(inputBuf.length, 128), inputBuf); +} +exports.encode = encode; +/** + * Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array. + * E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw. + * @param input + * @param start + * @param end + */ +function safeSlice(input, start, end) { + if (end > input.length) { + throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds'); + } + return input.slice(start, end); +} +/** + * Parse integers. Check if there is no leading zeros + * @param v The value to parse + */ +function decodeLength(v) { + if (v[0] === 0) { + throw new Error('invalid RLP: extra zeros'); + } + return parseHexByte(bytesToHex(v)); +} +function encodeLength(len, offset) { + if (len < 56) { + return Uint8Array.from([len + offset]); + } + const hexLength = numberToHex(len); + const lLength = hexLength.length / 2; + const firstByte = numberToHex(offset + 55 + lLength); + return Uint8Array.from(hexToBytes(firstByte + hexLength)); +} +function decode(input, stream = false) { + if (typeof input === 'undefined' || input === null || input.length === 0) { + return Uint8Array.from([]); + } + const inputBytes = toBytes(input); + const decoded = _decode(inputBytes); + if (stream) { + return decoded; + } + if (decoded.remainder.length !== 0) { + throw new Error('invalid RLP: remainder must be zero'); + } + return decoded.data; +} +exports.decode = decode; +/** Decode an input with RLP */ +function _decode(input) { + let length, llength, data, innerRemainder, d; + const decoded = []; + const firstByte = input[0]; + if (firstByte <= 0x7f) { + // a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. + return { + data: input.slice(0, 1), + remainder: input.slice(1), + }; + } + else if (firstByte <= 0xb7) { + // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string + // The range of the first byte is [0x80, 0xb7] + length = firstByte - 0x7f; + // set 0x80 null to 0 + if (firstByte === 0x80) { + data = Uint8Array.from([]); + } + else { + data = safeSlice(input, 1, length); + } + if (length === 2 && data[0] < 0x80) { + throw new Error('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed'); + } + return { + data, + remainder: input.slice(length), + }; + } + else if (firstByte <= 0xbf) { + // string is greater than 55 bytes long. A single byte with the value (0xb7 plus the length of the length), + // followed by the length, followed by the string + llength = firstByte - 0xb6; + if (input.length - 1 < llength) { + throw new Error('invalid RLP: not enough bytes for string length'); + } + length = decodeLength(safeSlice(input, 1, llength)); + if (length <= 55) { + throw new Error('invalid RLP: expected string length to be greater than 55'); + } + data = safeSlice(input, llength, length + llength); + return { + data, + remainder: input.slice(length + llength), + }; + } + else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + length = firstByte - 0xbf; + innerRemainder = safeSlice(input, 1, length); + while (innerRemainder.length) { + d = _decode(innerRemainder); + decoded.push(d.data); + innerRemainder = d.remainder; + } + return { + data: decoded, + remainder: input.slice(length), + }; + } + else { + // a list over 55 bytes long + llength = firstByte - 0xf6; + length = decodeLength(safeSlice(input, 1, llength)); + if (length < 56) { + throw new Error('invalid RLP: encoded list too short'); + } + const totalLength = llength + length; + if (totalLength > input.length) { + throw new Error('invalid RLP: total length is larger than the data'); + } + innerRemainder = safeSlice(input, llength, totalLength); + while (innerRemainder.length) { + d = _decode(innerRemainder); + decoded.push(d.data); + innerRemainder = d.remainder; + } + return { + data: decoded, + remainder: input.slice(totalLength), + }; + } +} +const cachedHexes = Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0')); +function bytesToHex(uint8a) { + // Pre-caching chars with `cachedHexes` speeds this up 6x + let hex = ''; + for (let i = 0; i < uint8a.length; i++) { + hex += cachedHexes[uint8a[i]]; + } + return hex; +} +function parseHexByte(hexByte) { + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte)) + throw new Error('Invalid byte sequence'); + return byte; +} +// Caching slows it down 2-3x +function hexToBytes(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + typeof hex); + } + if (hex.length % 2) + throw new Error('hexToBytes: received invalid unpadded hex'); + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + array[i] = parseHexByte(hex.slice(j, j + 2)); + } + return array; +} +/** Concatenates two Uint8Arrays into one. */ +function concatBytes(...arrays) { + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +function utf8ToBytes(utf) { + return new TextEncoder().encode(utf); +} +/** Transform an integer into its hexadecimal value */ +function numberToHex(integer) { + if (integer < 0) { + throw new Error('Invalid integer as argument, must be unsigned!'); + } + const hex = integer.toString(16); + return hex.length % 2 ? `0${hex}` : hex; +} +/** Pad a string to be even */ +function padToEven(a) { + return a.length % 2 ? `0${a}` : a; +} +/** Check if a string is prefixed by 0x */ +function isHexPrefixed(str) { + return str.length >= 2 && str[0] === '0' && str[1] === 'x'; +} +/** Removes 0x from a given String */ +function stripHexPrefix(str) { + if (typeof str !== 'string') { + return str; + } + return isHexPrefixed(str) ? str.slice(2) : str; +} +/** Transform anything into a Uint8Array */ +function toBytes(v) { + if (v instanceof Uint8Array) { + return v; + } + if (typeof v === 'string') { + if (isHexPrefixed(v)) { + return hexToBytes(padToEven(stripHexPrefix(v))); + } + return utf8ToBytes(v); + } + if (typeof v === 'number' || typeof v === 'bigint') { + if (!v) { + return Uint8Array.from([]); + } + return hexToBytes(numberToHex(v)); + } + if (v === null || v === undefined) { + return Uint8Array.from([]); + } + throw new Error('toBytes: received unsupported type ' + typeof v); +} +exports.utils = { + bytesToHex, + concatBytes, + hexToBytes, + utf8ToBytes, +}; +exports.RLP = { encode, decode }; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 16284: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.accountBodyToRLP = exports.accountBodyToSlim = exports.accountBodyFromSlim = exports.isZeroAddress = exports.zeroAddress = exports.importPublic = exports.privateToAddress = exports.privateToPublic = exports.publicToAddress = exports.pubToAddress = exports.isValidPublic = exports.isValidPrivate = exports.generateAddress2 = exports.generateAddress = exports.isValidChecksumAddress = exports.toChecksumAddress = exports.isValidAddress = exports.Account = void 0; +const rlp_1 = __webpack_require__(66289); +const keccak_1 = __webpack_require__(32019); +const secp256k1_1 = __webpack_require__(26513); +const utils_1 = __webpack_require__(82672); +const bytes_1 = __webpack_require__(77312); +const constants_1 = __webpack_require__(89838); +const helpers_1 = __webpack_require__(35546); +const internal_1 = __webpack_require__(59498); +const _0n = BigInt(0); +class Account { + /** + * This constructor assigns and validates the values. + * Use the static factory methods to assist in creating an Account from varying data types. + */ + constructor(nonce = _0n, balance = _0n, storageRoot = constants_1.KECCAK256_RLP, codeHash = constants_1.KECCAK256_NULL) { + this.nonce = nonce; + this.balance = balance; + this.storageRoot = storageRoot; + this.codeHash = codeHash; + this._validate(); + } + static fromAccountData(accountData) { + const { nonce, balance, storageRoot, codeHash } = accountData; + return new Account(nonce !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(nonce)) : undefined, balance !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(balance)) : undefined, storageRoot !== undefined ? (0, bytes_1.toBuffer)(storageRoot) : undefined, codeHash !== undefined ? (0, bytes_1.toBuffer)(codeHash) : undefined); + } + static fromRlpSerializedAccount(serialized) { + const values = (0, bytes_1.arrToBufArr)(rlp_1.RLP.decode(Uint8Array.from(serialized))); + if (!Array.isArray(values)) { + throw new Error('Invalid serialized account input. Must be array'); + } + return this.fromValuesArray(values); + } + static fromValuesArray(values) { + const [nonce, balance, storageRoot, codeHash] = values; + return new Account((0, bytes_1.bufferToBigInt)(nonce), (0, bytes_1.bufferToBigInt)(balance), storageRoot, codeHash); + } + _validate() { + if (this.nonce < _0n) { + throw new Error('nonce must be greater than zero'); + } + if (this.balance < _0n) { + throw new Error('balance must be greater than zero'); + } + if (this.storageRoot.length !== 32) { + throw new Error('storageRoot must have a length of 32'); + } + if (this.codeHash.length !== 32) { + throw new Error('codeHash must have a length of 32'); + } + } + /** + * Returns a Buffer Array of the raw Buffers for the account, in order. + */ + raw() { + return [ + (0, bytes_1.bigIntToUnpaddedBuffer)(this.nonce), + (0, bytes_1.bigIntToUnpaddedBuffer)(this.balance), + this.storageRoot, + this.codeHash, + ]; + } + /** + * Returns the RLP serialization of the account as a `Buffer`. + */ + serialize() { + return Buffer.from(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)(this.raw()))); + } + /** + * Returns a `Boolean` determining if the account is a contract. + */ + isContract() { + return !this.codeHash.equals(constants_1.KECCAK256_NULL); + } + /** + * Returns a `Boolean` determining if the account is empty complying to the definition of + * account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): + * "An account is considered empty when it has no code and zero nonce and zero balance." + */ + isEmpty() { + return this.balance === _0n && this.nonce === _0n && this.codeHash.equals(constants_1.KECCAK256_NULL); + } +} +exports.Account = Account; +/** + * Checks if the address is a valid. Accepts checksummed addresses too. + */ +const isValidAddress = function (hexAddress) { + try { + (0, helpers_1.assertIsString)(hexAddress); + } + catch (e) { + return false; + } + return /^0x[0-9a-fA-F]{40}$/.test(hexAddress); +}; +exports.isValidAddress = isValidAddress; +/** + * Returns a checksummed address. + * + * If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This + * has the effect of checksummed addresses for one chain having invalid checksums for others. + * For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191). + * + * WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not + * backwards compatible to the original widely adopted checksum format standard introduced in + * [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. + * Usage of this EIP is therefore discouraged unless you have a very targeted use case. + */ +const toChecksumAddress = function (hexAddress, eip1191ChainId) { + (0, helpers_1.assertIsHexString)(hexAddress); + const address = (0, internal_1.stripHexPrefix)(hexAddress).toLowerCase(); + let prefix = ''; + if (eip1191ChainId !== undefined) { + const chainId = (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(eip1191ChainId)); + prefix = chainId.toString() + '0x'; + } + const buf = Buffer.from(prefix + address, 'utf8'); + const hash = (0, utils_1.bytesToHex)((0, keccak_1.keccak256)(buf)); + let ret = '0x'; + for (let i = 0; i < address.length; i++) { + if (parseInt(hash[i], 16) >= 8) { + ret += address[i].toUpperCase(); + } + else { + ret += address[i]; + } + } + return ret; +}; +exports.toChecksumAddress = toChecksumAddress; +/** + * Checks if the address is a valid checksummed address. + * + * See toChecksumAddress' documentation for details about the eip1191ChainId parameter. + */ +const isValidChecksumAddress = function (hexAddress, eip1191ChainId) { + return (0, exports.isValidAddress)(hexAddress) && (0, exports.toChecksumAddress)(hexAddress, eip1191ChainId) === hexAddress; +}; +exports.isValidChecksumAddress = isValidChecksumAddress; +/** + * Generates an address of a newly created contract. + * @param from The address which is creating this new address + * @param nonce The nonce of the from account + */ +const generateAddress = function (from, nonce) { + (0, helpers_1.assertIsBuffer)(from); + (0, helpers_1.assertIsBuffer)(nonce); + if ((0, bytes_1.bufferToBigInt)(nonce) === BigInt(0)) { + // in RLP we want to encode null in the case of zero nonce + // read the RLP documentation for an answer if you dare + return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, null])))).slice(-20); + } + // Only take the lower 160bits of the hash + return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, nonce])))).slice(-20); +}; +exports.generateAddress = generateAddress; +/** + * Generates an address for a contract created using CREATE2. + * @param from The address which is creating this new address + * @param salt A salt + * @param initCode The init code of the contract being created + */ +const generateAddress2 = function (from, salt, initCode) { + (0, helpers_1.assertIsBuffer)(from); + (0, helpers_1.assertIsBuffer)(salt); + (0, helpers_1.assertIsBuffer)(initCode); + if (from.length !== 20) { + throw new Error('Expected from to be of length 20'); + } + if (salt.length !== 32) { + throw new Error('Expected salt to be of length 32'); + } + const address = (0, keccak_1.keccak256)(Buffer.concat([Buffer.from('ff', 'hex'), from, salt, (0, keccak_1.keccak256)(initCode)])); + return (0, bytes_1.toBuffer)(address).slice(-20); +}; +exports.generateAddress2 = generateAddress2; +/** + * Checks if the private key satisfies the rules of the curve secp256k1. + */ +const isValidPrivate = function (privateKey) { + return secp256k1_1.secp256k1.utils.isValidPrivateKey(privateKey); +}; +exports.isValidPrivate = isValidPrivate; +/** + * Checks if the public key satisfies the rules of the curve secp256k1 + * and the requirements of Ethereum. + * @param publicKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ +const isValidPublic = function (publicKey, sanitize = false) { + (0, helpers_1.assertIsBuffer)(publicKey); + if (publicKey.length === 64) { + // Convert to SEC1 for secp256k1 + // Automatically checks whether point is on curve + try { + secp256k1_1.secp256k1.ProjectivePoint.fromHex(Buffer.concat([Buffer.from([4]), publicKey])); + return true; + } + catch (e) { + return false; + } + } + if (!sanitize) { + return false; + } + try { + secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey); + return true; + } + catch (e) { + return false; + } +}; +exports.isValidPublic = isValidPublic; +/** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param sanitize Accept public keys in other formats + */ +const pubToAddress = function (pubKey, sanitize = false) { + (0, helpers_1.assertIsBuffer)(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1)); + } + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64'); + } + // Only take the lower 160bits of the hash + return Buffer.from((0, keccak_1.keccak256)(pubKey)).slice(-20); +}; +exports.pubToAddress = pubToAddress; +exports.publicToAddress = exports.pubToAddress; +/** + * Returns the ethereum public key of a given private key. + * @param privateKey A private key must be 256 bits wide + */ +const privateToPublic = function (privateKey) { + (0, helpers_1.assertIsBuffer)(privateKey); + // skip the type flag and use the X, Y points + return Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(false).slice(1)); +}; +exports.privateToPublic = privateToPublic; +/** + * Returns the ethereum address of a given private key. + * @param privateKey A private key must be 256 bits wide + */ +const privateToAddress = function (privateKey) { + return (0, exports.publicToAddress)((0, exports.privateToPublic)(privateKey)); +}; +exports.privateToAddress = privateToAddress; +/** + * Converts a public key to the Ethereum format. + */ +const importPublic = function (publicKey) { + (0, helpers_1.assertIsBuffer)(publicKey); + if (publicKey.length !== 64) { + publicKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(false).slice(1)); + } + return publicKey; +}; +exports.importPublic = importPublic; +/** + * Returns the zero address. + */ +const zeroAddress = function () { + const addressLength = 20; + const addr = (0, bytes_1.zeros)(addressLength); + return (0, bytes_1.bufferToHex)(addr); +}; +exports.zeroAddress = zeroAddress; +/** + * Checks if a given address is the zero address. + */ +const isZeroAddress = function (hexAddress) { + try { + (0, helpers_1.assertIsString)(hexAddress); + } + catch (e) { + return false; + } + const zeroAddr = (0, exports.zeroAddress)(); + return zeroAddr === hexAddress; +}; +exports.isZeroAddress = isZeroAddress; +function accountBodyFromSlim(body) { + const [nonce, balance, storageRoot, codeHash] = body; + return [ + nonce, + balance, + (0, bytes_1.arrToBufArr)(storageRoot).length === 0 ? constants_1.KECCAK256_RLP : storageRoot, + (0, bytes_1.arrToBufArr)(codeHash).length === 0 ? constants_1.KECCAK256_NULL : codeHash, + ]; +} +exports.accountBodyFromSlim = accountBodyFromSlim; +const emptyUint8Arr = new Uint8Array(0); +function accountBodyToSlim(body) { + const [nonce, balance, storageRoot, codeHash] = body; + return [ + nonce, + balance, + (0, bytes_1.arrToBufArr)(storageRoot).equals(constants_1.KECCAK256_RLP) ? emptyUint8Arr : storageRoot, + (0, bytes_1.arrToBufArr)(codeHash).equals(constants_1.KECCAK256_NULL) ? emptyUint8Arr : codeHash, + ]; +} +exports.accountBodyToSlim = accountBodyToSlim; +/** + * Converts a slim account (per snap protocol spec) to the RLP encoded version of the account + * @param body Array of 4 Buffer-like items to represent the account + * @returns RLP encoded version of the account + */ +function accountBodyToRLP(body, couldBeSlim = true) { + const accountBody = couldBeSlim ? accountBodyFromSlim(body) : body; + return (0, bytes_1.arrToBufArr)(rlp_1.RLP.encode(accountBody)); +} +exports.accountBodyToRLP = accountBodyToRLP; +//# sourceMappingURL=account.js.map + +/***/ }), + +/***/ 86727: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Address = void 0; +const account_1 = __webpack_require__(16284); +const bytes_1 = __webpack_require__(77312); +/** + * Handling and generating Ethereum addresses + */ +class Address { + constructor(buf) { + if (buf.length !== 20) { + throw new Error('Invalid address length'); + } + this.buf = buf; + } + /** + * Returns the zero address. + */ + static zero() { + return new Address((0, bytes_1.zeros)(20)); + } + /** + * Returns an Address object from a hex-encoded string. + * @param str - Hex-encoded address + */ + static fromString(str) { + if (!(0, account_1.isValidAddress)(str)) { + throw new Error('Invalid address'); + } + return new Address((0, bytes_1.toBuffer)(str)); + } + /** + * Returns an address for a given public key. + * @param pubKey The two points of an uncompressed key + */ + static fromPublicKey(pubKey) { + if (!Buffer.isBuffer(pubKey)) { + throw new Error('Public key should be Buffer'); + } + const buf = (0, account_1.pubToAddress)(pubKey); + return new Address(buf); + } + /** + * Returns an address for a given private key. + * @param privateKey A private key must be 256 bits wide + */ + static fromPrivateKey(privateKey) { + if (!Buffer.isBuffer(privateKey)) { + throw new Error('Private key should be Buffer'); + } + const buf = (0, account_1.privateToAddress)(privateKey); + return new Address(buf); + } + /** + * Generates an address for a newly created contract. + * @param from The address which is creating this new address + * @param nonce The nonce of the from account + */ + static generate(from, nonce) { + if (typeof nonce !== 'bigint') { + throw new Error('Expected nonce to be a bigint'); + } + return new Address((0, account_1.generateAddress)(from.buf, (0, bytes_1.bigIntToBuffer)(nonce))); + } + /** + * Generates an address for a contract created using CREATE2. + * @param from The address which is creating this new address + * @param salt A salt + * @param initCode The init code of the contract being created + */ + static generate2(from, salt, initCode) { + if (!Buffer.isBuffer(salt)) { + throw new Error('Expected salt to be a Buffer'); + } + if (!Buffer.isBuffer(initCode)) { + throw new Error('Expected initCode to be a Buffer'); + } + return new Address((0, account_1.generateAddress2)(from.buf, salt, initCode)); + } + /** + * Is address equal to another. + */ + equals(address) { + return this.buf.equals(address.buf); + } + /** + * Is address zero. + */ + isZero() { + return this.equals(Address.zero()); + } + /** + * True if address is in the address range defined + * by EIP-1352 + */ + isPrecompileOrSystemAddress() { + const address = (0, bytes_1.bufferToBigInt)(this.buf); + const rangeMin = BigInt(0); + const rangeMax = BigInt('0xffff'); + return address >= rangeMin && address <= rangeMax; + } + /** + * Returns hex encoding of address. + */ + toString() { + return '0x' + this.buf.toString('hex'); + } + /** + * Returns Buffer representation of address. + */ + toBuffer() { + return Buffer.from(this.buf); + } +} +exports.Address = Address; +//# sourceMappingURL=address.js.map + +/***/ }), + +/***/ 98421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +/** + * Ported to Typescript from original implementation below: + * https://github.com/ahultgren/async-eventemitter -- MIT licensed + * + * Type Definitions based on work by: patarapolw -- MIT licensed + * that was contributed to Definitely Typed below: + * https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AsyncEventEmitter = void 0; +const events_1 = __webpack_require__(37007); +async function runInSeries(context, tasks, data) { + let error; + for await (const task of tasks) { + try { + if (task.length < 2) { + //sync + task.call(context, data); + } + else { + await new Promise((resolve, reject) => { + task.call(context, data, (error) => { + if (error) { + reject(error); + } + else { + resolve(); + } + }); + }); + } + } + catch (e) { + error = e; + } + } + if (error) { + throw error; + } +} +class AsyncEventEmitter extends events_1.EventEmitter { + emit(event, ...args) { + let [data, callback] = args; + const self = this; + let listeners = self._events[event] ?? []; + // Optional data argument + if (callback === undefined && typeof data === 'function') { + callback = data; + data = undefined; + } + // Special treatment of internal newListener and removeListener events + if (event === 'newListener' || event === 'removeListener') { + data = { + event: data, + fn: callback, + }; + callback = undefined; + } + // A single listener is just a function not an array... + listeners = Array.isArray(listeners) ? listeners : [listeners]; + runInSeries(self, listeners.slice(), data).then(callback).catch(callback); + return self.listenerCount(event) > 0; + } + once(event, listener) { + const self = this; + let g; + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function'); + } + // Hack to support set arity + if (listener.length >= 2) { + g = function (e, next) { + self.removeListener(event, g); + void listener(e, next); + }; + } + else { + g = function (e) { + self.removeListener(event, g); + void listener(e, g); + }; + } + self.on(event, g); + return self; + } + first(event, listener) { + let listeners = this._events[event] ?? []; + // Contract + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function'); + } + // Listeners are not always an array + if (!Array.isArray(listeners)) { + ; + this._events[event] = listeners = [listeners]; + } + listeners.unshift(listener); + return this; + } + before(event, target, listener) { + return this.beforeOrAfter(event, target, listener); + } + after(event, target, listener) { + return this.beforeOrAfter(event, target, listener, 'after'); + } + beforeOrAfter(event, target, listener, beforeOrAfter) { + let listeners = this._events[event] ?? []; + let i; + let index; + const add = beforeOrAfter === 'after' ? 1 : 0; + // Contract + if (typeof listener !== 'function') { + throw new TypeError('listener must be a function'); + } + if (typeof target !== 'function') { + throw new TypeError('target must be a function'); + } + // Listeners are not always an array + if (!Array.isArray(listeners)) { + ; + this._events[event] = listeners = [listeners]; + } + index = listeners.length; + for (i = listeners.length; i--;) { + if (listeners[i] === target) { + index = i + add; + break; + } + } + listeners.splice(index, 0, listener); + return this; + } + on(event, listener) { + return super.on(event, listener); + } + addListener(event, listener) { + return super.addListener(event, listener); + } + prependListener(event, listener) { + return super.prependListener(event, listener); + } + prependOnceListener(event, listener) { + return super.prependOnceListener(event, listener); + } + removeAllListeners(event) { + return super.removeAllListeners(event); + } + removeListener(event, listener) { + return super.removeListener(event, listener); + } + eventNames() { + return super.eventNames(); + } + listeners(event) { + return super.listeners(event); + } + listenerCount(event) { + return super.listenerCount(event); + } + getMaxListeners() { + return super.getMaxListeners(); + } + setMaxListeners(maxListeners) { + return super.setMaxListeners(maxListeners); + } +} +exports.AsyncEventEmitter = AsyncEventEmitter; +//# sourceMappingURL=asyncEventEmitter.js.map + +/***/ }), + +/***/ 77312: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.intToUnpaddedBuffer = exports.bigIntToUnpaddedBuffer = exports.bigIntToHex = exports.bufArrToArr = exports.arrToBufArr = exports.validateNoLeadingZeroes = exports.baToJSON = exports.toUtf8 = exports.short = exports.addHexPrefix = exports.toUnsigned = exports.fromSigned = exports.bufferToInt = exports.bigIntToBuffer = exports.bufferToBigInt = exports.bufferToHex = exports.toBuffer = exports.unpadHexString = exports.unpadArray = exports.unpadBuffer = exports.setLengthRight = exports.setLengthLeft = exports.zeros = exports.intToBuffer = exports.intToHex = void 0; +const helpers_1 = __webpack_require__(35546); +const internal_1 = __webpack_require__(59498); +/** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ +const intToHex = function (i) { + if (!Number.isSafeInteger(i) || i < 0) { + throw new Error(`Received an invalid integer type: ${i}`); + } + return `0x${i.toString(16)}`; +}; +exports.intToHex = intToHex; +/** + * Converts an `Number` to a `Buffer` + * @param {Number} i + * @return {Buffer} + */ +const intToBuffer = function (i) { + const hex = (0, exports.intToHex)(i); + return Buffer.from((0, internal_1.padToEven)(hex.slice(2)), 'hex'); +}; +exports.intToBuffer = intToBuffer; +/** + * Returns a buffer filled with 0s. + * @param bytes the number of bytes the buffer should be + */ +const zeros = function (bytes) { + return Buffer.allocUnsafe(bytes).fill(0); +}; +exports.zeros = zeros; +/** + * Pads a `Buffer` with zeros till it has `length` bytes. + * Truncates the beginning or end of input if its length exceeds `length`. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @param right whether to start padding form the left or right + * @return (Buffer) + */ +const setLength = function (msg, length, right) { + const buf = (0, exports.zeros)(length); + if (right) { + if (msg.length < length) { + msg.copy(buf); + return buf; + } + return msg.slice(0, length); + } + else { + if (msg.length < length) { + msg.copy(buf, length - msg.length); + return buf; + } + return msg.slice(-length); + } +}; +/** + * Left Pads a `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @return (Buffer) + */ +const setLengthLeft = function (msg, length) { + (0, helpers_1.assertIsBuffer)(msg); + return setLength(msg, length, false); +}; +exports.setLengthLeft = setLengthLeft; +/** + * Right Pads a `Buffer` with trailing zeros till it has `length` bytes. + * it truncates the end if it exceeds. + * @param msg the value to pad (Buffer) + * @param length the number of bytes the output should be + * @return (Buffer) + */ +const setLengthRight = function (msg, length) { + (0, helpers_1.assertIsBuffer)(msg); + return setLength(msg, length, true); +}; +exports.setLengthRight = setLengthRight; +/** + * Trims leading zeros from a `Buffer`, `String` or `Number[]`. + * @param a (Buffer|Array|String) + * @return (Buffer|Array|String) + */ +const stripZeros = function (a) { + let first = a[0]; + while (a.length > 0 && first.toString() === '0') { + a = a.slice(1); + first = a[0]; + } + return a; +}; +/** + * Trims leading zeros from a `Buffer`. + * @param a (Buffer) + * @return (Buffer) + */ +const unpadBuffer = function (a) { + (0, helpers_1.assertIsBuffer)(a); + return stripZeros(a); +}; +exports.unpadBuffer = unpadBuffer; +/** + * Trims leading zeros from an `Array` (of numbers). + * @param a (number[]) + * @return (number[]) + */ +const unpadArray = function (a) { + (0, helpers_1.assertIsArray)(a); + return stripZeros(a); +}; +exports.unpadArray = unpadArray; +/** + * Trims leading zeros from a hex-prefixed `String`. + * @param a (String) + * @return (String) + */ +const unpadHexString = function (a) { + (0, helpers_1.assertIsHexString)(a); + a = (0, internal_1.stripHexPrefix)(a); + return ('0x' + stripZeros(a)); +}; +exports.unpadHexString = unpadHexString; +/** + * Attempts to turn a value into a `Buffer`. + * Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects + * with a `toArray()` or `toBuffer()` method. + * @param v the value + */ +const toBuffer = function (v) { + if (v === null || v === undefined) { + return Buffer.allocUnsafe(0); + } + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } + if (Array.isArray(v) || v instanceof Uint8Array) { + return Buffer.from(v); + } + if (typeof v === 'string') { + if (!(0, internal_1.isHexString)(v)) { + throw new Error(`Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ${v}`); + } + return Buffer.from((0, internal_1.padToEven)((0, internal_1.stripHexPrefix)(v)), 'hex'); + } + if (typeof v === 'number') { + return (0, exports.intToBuffer)(v); + } + if (typeof v === 'bigint') { + if (v < BigInt(0)) { + throw new Error(`Cannot convert negative bigint to buffer. Given: ${v}`); + } + let n = v.toString(16); + if (n.length % 2) + n = '0' + n; + return Buffer.from(n, 'hex'); + } + if (v.toArray) { + // converts a BN to a Buffer + return Buffer.from(v.toArray()); + } + if (v.toBuffer) { + return Buffer.from(v.toBuffer()); + } + throw new Error('invalid type'); +}; +exports.toBuffer = toBuffer; +/** + * Converts a `Buffer` into a `0x`-prefixed hex `String`. + * @param buf `Buffer` object to convert + */ +const bufferToHex = function (buf) { + buf = (0, exports.toBuffer)(buf); + return '0x' + buf.toString('hex'); +}; +exports.bufferToHex = bufferToHex; +/** + * Converts a {@link Buffer} to a {@link bigint} + */ +function bufferToBigInt(buf) { + const hex = (0, exports.bufferToHex)(buf); + if (hex === '0x') { + return BigInt(0); + } + return BigInt(hex); +} +exports.bufferToBigInt = bufferToBigInt; +/** + * Converts a {@link bigint} to a {@link Buffer} + */ +function bigIntToBuffer(num) { + return (0, exports.toBuffer)('0x' + num.toString(16)); +} +exports.bigIntToBuffer = bigIntToBuffer; +/** + * Converts a `Buffer` to a `Number`. + * @param buf `Buffer` object to convert + * @throws If the input number exceeds 53 bits. + */ +const bufferToInt = function (buf) { + const res = Number(bufferToBigInt(buf)); + if (!Number.isSafeInteger(res)) + throw new Error('Number exceeds 53 bits'); + return res; +}; +exports.bufferToInt = bufferToInt; +/** + * Interprets a `Buffer` as a signed integer and returns a `BigInt`. Assumes 256-bit numbers. + * @param num Signed integer value + */ +const fromSigned = function (num) { + return BigInt.asIntN(256, bufferToBigInt(num)); +}; +exports.fromSigned = fromSigned; +/** + * Converts a `BigInt` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. + * @param num + */ +const toUnsigned = function (num) { + return bigIntToBuffer(BigInt.asUintN(256, num)); +}; +exports.toUnsigned = toUnsigned; +/** + * Adds "0x" to a given `String` if it does not already start with "0x". + */ +const addHexPrefix = function (str) { + if (typeof str !== 'string') { + return str; + } + return (0, internal_1.isHexPrefixed)(str) ? str : '0x' + str; +}; +exports.addHexPrefix = addHexPrefix; +/** + * Shortens a string or buffer's hex string representation to maxLength (default 50). + * + * Examples: + * + * Input: '657468657265756d000000000000000000000000000000000000000000000000' + * Output: '657468657265756d0000000000000000000000000000000000…' + */ +function short(buffer, maxLength = 50) { + const bufferStr = Buffer.isBuffer(buffer) ? buffer.toString('hex') : buffer; + if (bufferStr.length <= maxLength) { + return bufferStr; + } + return bufferStr.slice(0, maxLength) + '…'; +} +exports.short = short; +/** + * Returns the utf8 string representation from a hex string. + * + * Examples: + * + * Input 1: '657468657265756d000000000000000000000000000000000000000000000000' + * Input 2: '657468657265756d' + * Input 3: '000000000000000000000000000000000000000000000000657468657265756d' + * + * Output (all 3 input variants): 'ethereum' + * + * Note that this method is not intended to be used with hex strings + * representing quantities in both big endian or little endian notation. + * + * @param string Hex string, should be `0x` prefixed + * @return Utf8 string + */ +const toUtf8 = function (hex) { + const zerosRegexp = /^(00)+|(00)+$/g; + hex = (0, internal_1.stripHexPrefix)(hex); + if (hex.length % 2 !== 0) { + throw new Error('Invalid non-even hex string input for toUtf8() provided'); + } + const bufferVal = Buffer.from(hex.replace(zerosRegexp, ''), 'hex'); + return bufferVal.toString('utf8'); +}; +exports.toUtf8 = toUtf8; +/** + * Converts a `Buffer` or `Array` to JSON. + * @param ba (Buffer|Array) + * @return (Array|String|null) + */ +const baToJSON = function (ba) { + if (Buffer.isBuffer(ba)) { + return `0x${ba.toString('hex')}`; + } + else if (ba instanceof Array) { + const array = []; + for (let i = 0; i < ba.length; i++) { + array.push((0, exports.baToJSON)(ba[i])); + } + return array; + } +}; +exports.baToJSON = baToJSON; +/** + * Checks provided Buffers for leading zeroes and throws if found. + * + * Examples: + * + * Valid values: 0x1, 0x, 0x01, 0x1234 + * Invalid values: 0x0, 0x00, 0x001, 0x0001 + * + * Note: This method is useful for validating that RLP encoded integers comply with the rule that all + * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes + * @param values An object containing string keys and Buffer values + * @throws if any provided value is found to have leading zero bytes + */ +const validateNoLeadingZeroes = function (values) { + for (const [k, v] of Object.entries(values)) { + if (v !== undefined && v.length > 0 && v[0] === 0) { + throw new Error(`${k} cannot have leading zeroes, received: ${v.toString('hex')}`); + } + } +}; +exports.validateNoLeadingZeroes = validateNoLeadingZeroes; +function arrToBufArr(arr) { + if (!Array.isArray(arr)) { + return Buffer.from(arr); + } + return arr.map((a) => arrToBufArr(a)); +} +exports.arrToBufArr = arrToBufArr; +function bufArrToArr(arr) { + if (!Array.isArray(arr)) { + return Uint8Array.from(arr ?? []); + } + return arr.map((a) => bufArrToArr(a)); +} +exports.bufArrToArr = bufArrToArr; +/** + * Converts a {@link bigint} to a `0x` prefixed hex string + */ +const bigIntToHex = (num) => { + return '0x' + num.toString(16); +}; +exports.bigIntToHex = bigIntToHex; +/** + * Convert value from bigint to an unpadded Buffer + * (useful for RLP transport) + * @param value value to convert + */ +function bigIntToUnpaddedBuffer(value) { + return (0, exports.unpadBuffer)(bigIntToBuffer(value)); +} +exports.bigIntToUnpaddedBuffer = bigIntToUnpaddedBuffer; +function intToUnpaddedBuffer(value) { + return (0, exports.unpadBuffer)((0, exports.intToBuffer)(value)); +} +exports.intToUnpaddedBuffer = intToUnpaddedBuffer; +//# sourceMappingURL=bytes.js.map + +/***/ }), + +/***/ 89838: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MAX_WITHDRAWALS_PER_PAYLOAD = exports.RLP_EMPTY_STRING = exports.KECCAK256_RLP = exports.KECCAK256_RLP_S = exports.KECCAK256_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY_S = exports.KECCAK256_NULL = exports.KECCAK256_NULL_S = exports.TWO_POW256 = exports.SECP256K1_ORDER_DIV_2 = exports.SECP256K1_ORDER = exports.MAX_INTEGER_BIGINT = exports.MAX_INTEGER = exports.MAX_UINT64 = void 0; +const buffer_1 = __webpack_require__(48287); +const secp256k1_1 = __webpack_require__(26513); +/** + * 2^64-1 + */ +exports.MAX_UINT64 = BigInt('0xffffffffffffffff'); +/** + * The max integer that the evm can handle (2^256-1) + */ +exports.MAX_INTEGER = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +/** + * The max integer that the evm can handle (2^256-1) as a bigint + * 2^256-1 equals to 340282366920938463463374607431768211455 + * We use literal value instead of calculated value for compatibility issue. + */ +exports.MAX_INTEGER_BIGINT = BigInt('115792089237316195423570985008687907853269984665640564039457584007913129639935'); +exports.SECP256K1_ORDER = secp256k1_1.secp256k1.CURVE.n; +exports.SECP256K1_ORDER_DIV_2 = secp256k1_1.secp256k1.CURVE.n / BigInt(2); +/** + * 2^256 + */ +exports.TWO_POW256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); +/** + * Keccak-256 hash of null + */ +exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; +/** + * Keccak-256 hash of null + */ +exports.KECCAK256_NULL = buffer_1.Buffer.from(exports.KECCAK256_NULL_S, 'hex'); +/** + * Keccak-256 of an RLP of an empty array + */ +exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; +/** + * Keccak-256 of an RLP of an empty array + */ +exports.KECCAK256_RLP_ARRAY = buffer_1.Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); +/** + * Keccak-256 hash of the RLP of null + */ +exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; +/** + * Keccak-256 hash of the RLP of null + */ +exports.KECCAK256_RLP = buffer_1.Buffer.from(exports.KECCAK256_RLP_S, 'hex'); +/** + * RLP encoded empty string + */ +exports.RLP_EMPTY_STRING = buffer_1.Buffer.from([0x80]); +exports.MAX_WITHDRAWALS_PER_PAYLOAD = 16; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 45062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.compactBytesToNibbles = exports.bytesToNibbles = exports.nibblesToCompactBytes = exports.nibblesToBytes = exports.hasTerminator = void 0; +// Reference: https://ethereum.org/en/developers/docs/data-structures-and-encoding/patricia-merkle-trie/ +/** + * + * @param s byte sequence + * @returns boolean indicating if input hex nibble sequence has terminator indicating leaf-node + * terminator is represented with 16 because a nibble ranges from 0 - 15(f) + */ +const hasTerminator = (nibbles) => { + return nibbles.length > 0 && nibbles[nibbles.length - 1] === 16; +}; +exports.hasTerminator = hasTerminator; +const nibblesToBytes = (nibbles, bytes) => { + for (let bi = 0, ni = 0; ni < nibbles.length; bi += 1, ni += 2) { + bytes[bi] = (nibbles[ni] << 4) | nibbles[ni + 1]; + } +}; +exports.nibblesToBytes = nibblesToBytes; +const nibblesToCompactBytes = (nibbles) => { + let terminator = 0; + if ((0, exports.hasTerminator)(nibbles)) { + terminator = 1; + // Remove the terminator from the sequence + nibbles = nibbles.subarray(0, nibbles.length - 1); + } + const buf = new Uint8Array(nibbles.length / 2 + 1); + // Shift the terminator info into the first nibble of buf[0] + buf[0] = terminator << 5; + // If odd length, then add that flag into the first nibble and put the odd nibble to + // second part of buf[0] which otherwise will be left padded with a 0 + if ((nibbles.length & 1) === 1) { + buf[0] |= 1 << 4; + buf[0] |= nibbles[0]; + nibbles = nibbles.subarray(1); + } + // create bytes out of the rest even nibbles + (0, exports.nibblesToBytes)(nibbles, buf.subarray(1)); + return buf; +}; +exports.nibblesToCompactBytes = nibblesToCompactBytes; +const bytesToNibbles = (str) => { + const l = str.length * 2 + 1; + const nibbles = new Uint8Array(l); + for (let i = 0; i < str.length; i++) { + const b = str[i]; + nibbles[i * 2] = b / 16; + nibbles[i * 2 + 1] = b % 16; + } + // This will get removed from calling function if the first nibble + // indicates that terminator is not present + nibbles[l - 1] = 16; + return nibbles; +}; +exports.bytesToNibbles = bytesToNibbles; +const compactBytesToNibbles = (compact) => { + if (compact.length === 0) { + return compact; + } + let base = (0, exports.bytesToNibbles)(compact); + // delete terminator flag if terminator flag was not in first nibble + if (base[0] < 2) { + base = base.subarray(0, base.length - 1); + } + // chop the terminator nibble and the even padding (if there is one) + // i.e. chop 2 left nibbles when even else 1 when odd + const chop = 2 - (base[0] & 1); + return base.subarray(chop); +}; +exports.compactBytesToNibbles = compactBytesToNibbles; +/** + * A test helper to generates compact path for a subset of key bytes + * + * TODO: Commenting the code for now as this seems to be helper function + * (from geth codebase ) + * + */ +// +// +// export const getPathTo = (tillBytes: number, key: Buffer) => { +// const hexNibbles = bytesToNibbles(key).subarray(0, tillBytes) +// // Remove the terminator if its there, although it would be there only if tillBytes >= key.length +// // This seems to be a test helper to generate paths so correctness of this isn't necessary +// hexNibbles[hexNibbles.length - 1] = 0 +// const compactBytes = nibblesToCompactBytes(hexNibbles) +// return [Buffer.from(compactBytes)] +// } +//# sourceMappingURL=encoding.js.map + +/***/ }), + +/***/ 35546: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertIsString = exports.assertIsArray = exports.assertIsBuffer = exports.assertIsHexString = void 0; +const internal_1 = __webpack_require__(59498); +/** + * Throws if a string is not hex prefixed + * @param {string} input string to check hex prefix of + */ +const assertIsHexString = function (input) { + if (!(0, internal_1.isHexString)(input)) { + const msg = `This method only supports 0x-prefixed hex strings but input was: ${input}`; + throw new Error(msg); + } +}; +exports.assertIsHexString = assertIsHexString; +/** + * Throws if input is not a buffer + * @param {Buffer} input value to check + */ +const assertIsBuffer = function (input) { + if (!Buffer.isBuffer(input)) { + const msg = `This method only supports Buffer but input was: ${input}`; + throw new Error(msg); + } +}; +exports.assertIsBuffer = assertIsBuffer; +/** + * Throws if input is not an array + * @param {number[]} input value to check + */ +const assertIsArray = function (input) { + if (!Array.isArray(input)) { + const msg = `This method only supports number arrays but input was: ${input}`; + throw new Error(msg); + } +}; +exports.assertIsArray = assertIsArray; +/** + * Throws if input is not a string + * @param {string} input value to check + */ +const assertIsString = function (input) { + if (typeof input !== 'string') { + const msg = `This method only supports strings but input was: ${input}`; + throw new Error(msg); + } +}; +exports.assertIsString = assertIsString; +//# sourceMappingURL=helpers.js.map + +/***/ }), + +/***/ 68683: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toAscii = exports.stripHexPrefix = exports.padToEven = exports.isHexString = exports.isHexPrefixed = exports.getKeys = exports.getBinarySize = exports.fromUtf8 = exports.fromAscii = exports.arrayContainsArray = void 0; +/** + * Constants + */ +__exportStar(__webpack_require__(89838), exports); +/** + * Units helpers + */ +__exportStar(__webpack_require__(52652), exports); +/** + * Account class and helper functions + */ +__exportStar(__webpack_require__(16284), exports); +/** + * Address type + */ +__exportStar(__webpack_require__(86727), exports); +/** + * Withdrawal type + */ +__exportStar(__webpack_require__(37380), exports); +/** + * ECDSA signature + */ +__exportStar(__webpack_require__(92133), exports); +/** + * Utilities for manipulating Buffers, byte arrays, etc. + */ +__exportStar(__webpack_require__(77312), exports); +/** + * Helpful TypeScript types + */ +__exportStar(__webpack_require__(42666), exports); +/** + * Helper function for working with compact encoding + */ +__exportStar(__webpack_require__(45062), exports); +/** + * Export ethjs-util methods + */ +__exportStar(__webpack_require__(98421), exports); +var internal_1 = __webpack_require__(59498); +Object.defineProperty(exports, "arrayContainsArray", ({ enumerable: true, get: function () { return internal_1.arrayContainsArray; } })); +Object.defineProperty(exports, "fromAscii", ({ enumerable: true, get: function () { return internal_1.fromAscii; } })); +Object.defineProperty(exports, "fromUtf8", ({ enumerable: true, get: function () { return internal_1.fromUtf8; } })); +Object.defineProperty(exports, "getBinarySize", ({ enumerable: true, get: function () { return internal_1.getBinarySize; } })); +Object.defineProperty(exports, "getKeys", ({ enumerable: true, get: function () { return internal_1.getKeys; } })); +Object.defineProperty(exports, "isHexPrefixed", ({ enumerable: true, get: function () { return internal_1.isHexPrefixed; } })); +Object.defineProperty(exports, "isHexString", ({ enumerable: true, get: function () { return internal_1.isHexString; } })); +Object.defineProperty(exports, "padToEven", ({ enumerable: true, get: function () { return internal_1.padToEven; } })); +Object.defineProperty(exports, "stripHexPrefix", ({ enumerable: true, get: function () { return internal_1.stripHexPrefix; } })); +Object.defineProperty(exports, "toAscii", ({ enumerable: true, get: function () { return internal_1.toAscii; } })); +__exportStar(__webpack_require__(31708), exports); +__exportStar(__webpack_require__(81862), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 59498: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +/* +The MIT License + +Copyright (c) 2016 Nick Dodson. nickdodson.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isHexString = exports.getKeys = exports.fromAscii = exports.fromUtf8 = exports.toAscii = exports.arrayContainsArray = exports.getBinarySize = exports.padToEven = exports.stripHexPrefix = exports.isHexPrefixed = void 0; +/** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param str the string input value + * @return a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ +function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`); + } + return str[0] === '0' && str[1] === 'x'; +} +exports.isHexPrefixed = isHexPrefixed; +/** + * Removes '0x' from a given `String` if present + * @param str the string value + * @returns the string without 0x prefix + */ +const stripHexPrefix = (str) => { + if (typeof str !== 'string') + throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`); + return isHexPrefixed(str) ? str.slice(2) : str; +}; +exports.stripHexPrefix = stripHexPrefix; +/** + * Pads a `String` to have an even length + * @param value + * @return output + */ +function padToEven(value) { + let a = value; + if (typeof a !== 'string') { + throw new Error(`[padToEven] value must be type 'string', received ${typeof a}`); + } + if (a.length % 2) + a = `0${a}`; + return a; +} +exports.padToEven = padToEven; +/** + * Get the binary size of a string + * @param str + * @returns the number of bytes contained within the string + */ +function getBinarySize(str) { + if (typeof str !== 'string') { + throw new Error(`[getBinarySize] method requires input type 'string', received ${typeof str}`); + } + return Buffer.byteLength(str, 'utf8'); +} +exports.getBinarySize = getBinarySize; +/** + * Returns TRUE if the first specified array contains all elements + * from the second one. FALSE otherwise. + * + * @param superset + * @param subset + * + */ +function arrayContainsArray(superset, subset, some) { + if (Array.isArray(superset) !== true) { + throw new Error(`[arrayContainsArray] method requires input 'superset' to be an array, got type '${typeof superset}'`); + } + if (Array.isArray(subset) !== true) { + throw new Error(`[arrayContainsArray] method requires input 'subset' to be an array, got type '${typeof subset}'`); + } + return subset[some === true ? 'some' : 'every']((value) => superset.indexOf(value) >= 0); +} +exports.arrayContainsArray = arrayContainsArray; +/** + * Should be called to get ascii from its hex representation + * + * @param string in hex + * @returns ascii string representation of hex value + */ +function toAscii(hex) { + let str = ''; + let i = 0; + const l = hex.length; + if (hex.substring(0, 2) === '0x') + i = 2; + for (; i < l; i += 2) { + const code = parseInt(hex.substr(i, 2), 16); + str += String.fromCharCode(code); + } + return str; +} +exports.toAscii = toAscii; +/** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @param string + * @param optional padding + * @returns hex representation of input string + */ +function fromUtf8(stringValue) { + const str = Buffer.from(stringValue, 'utf8'); + return `0x${padToEven(str.toString('hex')).replace(/^0+|0+$/g, '')}`; +} +exports.fromUtf8 = fromUtf8; +/** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @param string + * @param optional padding + * @returns hex representation of input string + */ +function fromAscii(stringValue) { + let hex = ''; + for (let i = 0; i < stringValue.length; i++) { + const code = stringValue.charCodeAt(i); + const n = code.toString(16); + hex += n.length < 2 ? `0${n}` : n; + } + return `0x${hex}`; +} +exports.fromAscii = fromAscii; +/** + * Returns the keys from an array of objects. + * @example + * ```js + * getKeys([{a: '1', b: '2'}, {a: '3', b: '4'}], 'a') => ['1', '3'] + *```` + * @param params + * @param key + * @param allowEmpty + * @returns output just a simple array of output keys + */ +function getKeys(params, key, allowEmpty) { + if (!Array.isArray(params)) { + throw new Error(`[getKeys] method expects input 'params' to be an array, got ${typeof params}`); + } + if (typeof key !== 'string') { + throw new Error(`[getKeys] method expects input 'key' to be type 'string', got ${typeof params}`); + } + const result = []; + for (let i = 0; i < params.length; i++) { + let value = params[i][key]; + if (allowEmpty === true && !value) { + value = ''; + } + else if (typeof value !== 'string') { + throw new Error(`invalid abi - expected type 'string', received ${typeof value}`); + } + result.push(value); + } + return result; +} +exports.getKeys = getKeys; +/** + * Is the string a hex string. + * + * @param value + * @param length + * @returns output the string is a hex string + */ +function isHexString(value, length) { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) + return false; + if (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length) + return false; + return true; +} +exports.isHexString = isHexString; +//# sourceMappingURL=internal.js.map + +/***/ }), + +/***/ 31708: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(96763); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Lock = void 0; +// Based on https://github.com/jsoendermann/semaphore-async-await/blob/master/src/Semaphore.ts +class Lock { + constructor() { + this.permits = 1; + this.promiseResolverQueue = []; + } + /** + * Returns a promise used to wait for a permit to become available. This method should be awaited on. + * @returns A promise that gets resolved when execution is allowed to proceed. + */ + async acquire() { + if (this.permits > 0) { + this.permits -= 1; + return Promise.resolve(true); + } + // If there is no permit available, we return a promise that resolves once the semaphore gets + // signaled enough times that permits is equal to one. + return new Promise((resolver) => this.promiseResolverQueue.push(resolver)); + } + /** + * Increases the number of permits by one. If there are other functions waiting, one of them will + * continue to execute in a future iteration of the event loop. + */ + release() { + this.permits += 1; + if (this.permits > 1 && this.promiseResolverQueue.length > 0) { + // eslint-disable-next-line no-console + console.warn('Lock.permits should never be > 0 when there is someone waiting.'); + } + else if (this.permits === 1 && this.promiseResolverQueue.length > 0) { + // If there is someone else waiting, immediately consume the permit that was released + // at the beginning of this function and let the waiting function resume. + this.permits -= 1; + const nextResolver = this.promiseResolverQueue.shift(); + if (nextResolver) { + nextResolver(true); + } + } + } +} +exports.Lock = Lock; +//# sourceMappingURL=lock.js.map + +/***/ }), + +/***/ 81862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getProvider = exports.fetchFromProvider = void 0; +const micro_ftch_1 = __webpack_require__(6215); +const fetchFromProvider = async (url, params) => { + const res = await (0, micro_ftch_1.default)(url, { + headers: { + 'content-type': 'application/json', + }, + type: 'json', + data: { + method: params.method, + params: params.params, + jsonrpc: '2.0', + id: 1, + }, + }); + return res.result; +}; +exports.fetchFromProvider = fetchFromProvider; +const getProvider = (provider) => { + if (typeof provider === 'string') { + return provider; + } + else if (provider?.connection?.url !== undefined) { + return provider.connection.url; + } + else { + throw new Error('Must provide valid provider URL or Web3Provider'); + } +}; +exports.getProvider = getProvider; +//# sourceMappingURL=provider.js.map + +/***/ }), + +/***/ 92133: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashPersonalMessage = exports.isValidSignature = exports.fromRpcSig = exports.toCompactSig = exports.toRpcSig = exports.ecrecover = exports.ecsign = void 0; +const keccak_1 = __webpack_require__(32019); +const secp256k1_1 = __webpack_require__(26513); +const bytes_1 = __webpack_require__(77312); +const constants_1 = __webpack_require__(89838); +const helpers_1 = __webpack_require__(35546); +/** + * Returns the ECDSA signature of a message hash. + * + * If `chainId` is provided assume an EIP-155-style signature and calculate the `v` value + * accordingly, otherwise return a "static" `v` just derived from the `recovery` bit + */ +function ecsign(msgHash, privateKey, chainId) { + const sig = secp256k1_1.secp256k1.sign(msgHash, privateKey); + const buf = sig.toCompactRawBytes(); + const r = Buffer.from(buf.slice(0, 32)); + const s = Buffer.from(buf.slice(32, 64)); + const v = chainId === undefined + ? BigInt(sig.recovery + 27) + : BigInt(sig.recovery + 35) + BigInt(chainId) * BigInt(2); + return { r, s, v }; +} +exports.ecsign = ecsign; +function calculateSigRecovery(v, chainId) { + if (v === BigInt(0) || v === BigInt(1)) + return v; + if (chainId === undefined) { + return v - BigInt(27); + } + return v - (chainId * BigInt(2) + BigInt(35)); +} +function isValidSigRecovery(recovery) { + return recovery === BigInt(0) || recovery === BigInt(1); +} +/** + * ECDSA public key recovery from signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Recovered public key + */ +const ecrecover = function (msgHash, v, r, s, chainId) { + const signature = Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(s, 32)], 64); + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + const sig = secp256k1_1.secp256k1.Signature.fromCompact(signature).addRecoveryBit(Number(recovery)); + const senderPubKey = sig.recoverPublicKey(msgHash); + return Buffer.from(senderPubKey.toRawBytes(false).slice(1)); +}; +exports.ecrecover = ecrecover; +/** + * Convert signature parameters into the format of `eth_sign` RPC method. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Signature + */ +const toRpcSig = function (v, r, s, chainId) { + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin + return (0, bytes_1.bufferToHex)(Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(s, 32), (0, bytes_1.toBuffer)(v)])); +}; +exports.toRpcSig = toRpcSig; +/** + * Convert signature parameters into the format of Compact Signature Representation (EIP-2098). + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @returns Signature + */ +const toCompactSig = function (v, r, s, chainId) { + const recovery = calculateSigRecovery(v, chainId); + if (!isValidSigRecovery(recovery)) { + throw new Error('Invalid signature v value'); + } + let ss = s; + if ((v > BigInt(28) && v % BigInt(2) === BigInt(1)) || v === BigInt(1) || v === BigInt(28)) { + ss = Buffer.from(s); + ss[0] |= 0x80; + } + return (0, bytes_1.bufferToHex)(Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(ss, 32)])); +}; +exports.toCompactSig = toCompactSig; +/** + * Convert signature format of the `eth_sign` RPC method to signature parameters + * + * NOTE: For an extracted `v` value < 27 (see Geth bug https://github.com/ethereum/go-ethereum/issues/2053) + * `v + 27` is returned for the `v` value + * NOTE: After EIP1559, `v` could be `0` or `1` but this function assumes + * it's a signed message (EIP-191 or EIP-712) adding `27` at the end. Remove if needed. + */ +const fromRpcSig = function (sig) { + const buf = (0, bytes_1.toBuffer)(sig); + let r; + let s; + let v; + if (buf.length >= 65) { + r = buf.slice(0, 32); + s = buf.slice(32, 64); + v = (0, bytes_1.bufferToBigInt)(buf.slice(64)); + } + else if (buf.length === 64) { + // Compact Signature Representation (https://eips.ethereum.org/EIPS/eip-2098) + r = buf.slice(0, 32); + s = buf.slice(32, 64); + v = BigInt((0, bytes_1.bufferToInt)(buf.slice(32, 33)) >> 7); + s[0] &= 0x7f; + } + else { + throw new Error('Invalid signature length'); + } + // support both versions of `eth_sign` responses + if (v < 27) { + v = v + BigInt(27); + } + return { + v, + r, + s, + }; +}; +exports.fromRpcSig = fromRpcSig; +/** + * Validate a ECDSA signature. + * NOTE: Accepts `v === 0 | v === 1` for EIP1559 transactions + * @param homesteadOrLater Indicates whether this is being used on either the homestead hardfork or a later one + */ +const isValidSignature = function (v, r, s, homesteadOrLater = true, chainId) { + if (r.length !== 32 || s.length !== 32) { + return false; + } + if (!isValidSigRecovery(calculateSigRecovery(v, chainId))) { + return false; + } + const rBigInt = (0, bytes_1.bufferToBigInt)(r); + const sBigInt = (0, bytes_1.bufferToBigInt)(s); + if (rBigInt === BigInt(0) || + rBigInt >= constants_1.SECP256K1_ORDER || + sBigInt === BigInt(0) || + sBigInt >= constants_1.SECP256K1_ORDER) { + return false; + } + if (homesteadOrLater && sBigInt >= constants_1.SECP256K1_ORDER_DIV_2) { + return false; + } + return true; +}; +exports.isValidSignature = isValidSignature; +/** + * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. + * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` + * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key + * used to produce the signature. + */ +const hashPersonalMessage = function (message) { + (0, helpers_1.assertIsBuffer)(message); + const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${message.length}`, 'utf-8'); + return Buffer.from((0, keccak_1.keccak256)(Buffer.concat([prefix, message]))); +}; +exports.hashPersonalMessage = hashPersonalMessage; +//# sourceMappingURL=signature.js.map + +/***/ }), + +/***/ 42666: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toType = exports.TypeOutput = void 0; +const bytes_1 = __webpack_require__(77312); +const internal_1 = __webpack_require__(59498); +/** + * Type output options + */ +var TypeOutput; +(function (TypeOutput) { + TypeOutput[TypeOutput["Number"] = 0] = "Number"; + TypeOutput[TypeOutput["BigInt"] = 1] = "BigInt"; + TypeOutput[TypeOutput["Buffer"] = 2] = "Buffer"; + TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString"; +})(TypeOutput = exports.TypeOutput || (exports.TypeOutput = {})); +function toType(input, outputType) { + if (input === null) { + return null; + } + if (input === undefined) { + return undefined; + } + if (typeof input === 'string' && !(0, internal_1.isHexString)(input)) { + throw new Error(`A string must be provided with a 0x-prefix, given: ${input}`); + } + else if (typeof input === 'number' && !Number.isSafeInteger(input)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); + } + const output = (0, bytes_1.toBuffer)(input); + switch (outputType) { + case TypeOutput.Buffer: + return output; + case TypeOutput.BigInt: + return (0, bytes_1.bufferToBigInt)(output); + case TypeOutput.Number: { + const bigInt = (0, bytes_1.bufferToBigInt)(output); + if (bigInt > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)'); + } + return Number(bigInt); + } + case TypeOutput.PrefixedHexString: + return (0, bytes_1.bufferToHex)(output); + default: + throw new Error('unknown outputType'); + } +} +exports.toType = toType; +//# sourceMappingURL=types.js.map + +/***/ }), + +/***/ 52652: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GWEI_TO_WEI = void 0; +/** Easy conversion from Gwei to wei */ +exports.GWEI_TO_WEI = BigInt(1000000000); +//# sourceMappingURL=units.js.map + +/***/ }), + +/***/ 37380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Withdrawal = void 0; +const address_1 = __webpack_require__(86727); +const bytes_1 = __webpack_require__(77312); +const types_1 = __webpack_require__(42666); +/** + * Representation of EIP-4895 withdrawal data + */ +class Withdrawal { + /** + * This constructor assigns and validates the values. + * Use the static factory methods to assist in creating a Withdrawal object from varying data types. + * Its amount is in Gwei to match CL representation and for eventual ssz withdrawalsRoot + */ + constructor(index, validatorIndex, address, + /** + * withdrawal amount in Gwei to match the CL repesentation and eventually ssz withdrawalsRoot + */ + amount) { + this.index = index; + this.validatorIndex = validatorIndex; + this.address = address; + this.amount = amount; + } + static fromWithdrawalData(withdrawalData) { + const { index: indexData, validatorIndex: validatorIndexData, address: addressData, amount: amountData, } = withdrawalData; + const index = (0, types_1.toType)(indexData, types_1.TypeOutput.BigInt); + const validatorIndex = (0, types_1.toType)(validatorIndexData, types_1.TypeOutput.BigInt); + const address = new address_1.Address((0, types_1.toType)(addressData, types_1.TypeOutput.Buffer)); + const amount = (0, types_1.toType)(amountData, types_1.TypeOutput.BigInt); + return new Withdrawal(index, validatorIndex, address, amount); + } + static fromValuesArray(withdrawalArray) { + if (withdrawalArray.length !== 4) { + throw Error(`Invalid withdrawalArray length expected=4 actual=${withdrawalArray.length}`); + } + const [index, validatorIndex, address, amount] = withdrawalArray; + return Withdrawal.fromWithdrawalData({ index, validatorIndex, address, amount }); + } + /** + * Convert a withdrawal to a buffer array + * @param withdrawal the withdrawal to convert + * @returns buffer array of the withdrawal + */ + static toBufferArray(withdrawal) { + const { index, validatorIndex, address, amount } = withdrawal; + const indexBuffer = (0, types_1.toType)(index, types_1.TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : (0, types_1.toType)(index, types_1.TypeOutput.Buffer); + const validatorIndexBuffer = (0, types_1.toType)(validatorIndex, types_1.TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : (0, types_1.toType)(validatorIndex, types_1.TypeOutput.Buffer); + let addressBuffer; + if (address instanceof address_1.Address) { + addressBuffer = address.buf; + } + else { + addressBuffer = (0, types_1.toType)(address, types_1.TypeOutput.Buffer); + } + const amountBuffer = (0, types_1.toType)(amount, types_1.TypeOutput.BigInt) === BigInt(0) + ? Buffer.alloc(0) + : (0, types_1.toType)(amount, types_1.TypeOutput.Buffer); + return [indexBuffer, validatorIndexBuffer, addressBuffer, amountBuffer]; + } + raw() { + return Withdrawal.toBufferArray(this); + } + toValue() { + return { + index: this.index, + validatorIndex: this.validatorIndex, + address: this.address.buf, + amount: this.amount, + }; + } + toJSON() { + return { + index: (0, bytes_1.bigIntToHex)(this.index), + validatorIndex: (0, bytes_1.bigIntToHex)(this.validatorIndex), + address: '0x' + this.address.buf.toString('hex'), + amount: (0, bytes_1.bigIntToHex)(this.amount), + }; + } +} +exports.Withdrawal = Withdrawal; +//# sourceMappingURL=withdrawal.js.map + +/***/ }), + +/***/ 56498: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// ESLint gets confused by the nested list and tables in the docs, so we disable +// the rule for this file. +/* eslint-disable jsdoc/check-indentation, jsdoc/match-description */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decodeSingle = exports.decode = exports.encodePacked = exports.encodeSingle = exports.encode = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const packer_1 = __webpack_require__(37700); +/** + * Encode the data with the provided types. The types must be valid Solidity + * ABI types. + * + * This will attempt to parse the values into the correct types. For example, + * if you pass in a hex string for a `uint256`, it will be parsed into a + * `bigint`. Regular strings are interpreted as UTF-8 strings. If you want to + * pass in a hex string, you must pass it in as a `Uint8Array`, or use the + * "0x"-prefix. + * + * It will also attempt to infer the types of the values. For example, if you + * pass in a string for a `uint256`, it will result in a TypeScript compile-time + * error. This does not work for all types, however. For example, if you use + * nested arrays or tuples, the type will be inferred as `unknown`. + * + * The following types are supported: + * + * - `address`: A 20-byte Ethereum address. + * - As a 40-character-long hexadecimal string, starting with "0x". + * - As a 20-byte-long byte array, i.e., `Uint8Array`. + * - `bool`: A boolean value. + * - As a boolean literal, i.e., `true` or `false`. + * - As the strings "true" or "false". + * - `bytes(n)`: A dynamic byte array. + * - As a hexadecimal string, starting with "0x". + * - As a byte array, i.e., `Uint8Array`. + * - As a regular string, which will be interpreted as UTF-8. + * - `function`: A Solidity function. + * - As a 48-character-long hexadecimal string, starting with "0x". + * - As a 24-byte-long byte array, i.e., `Uint8Array`. + * - As a {@link SolidityFunction} object. + * - `int(n)`: A signed integer. + * - As a number. + * - As a `bigint`. + * - As a hexadecimal string, starting with "0x". + * - `string`: A dynamic UTF-8 string. + * - As a regular string. + * - As a hexadecimal string, starting with "0x". + * - As a byte array, i.e., `Uint8Array`. + * - `tuple`: A tuple of values. + * - As an array of values. + * - `uint(n)`: An unsigned integer. + * - As a number. + * - As a `bigint`. + * - As a hexadecimal string, starting with "0x". + * + * @example + * ```typescript + * import { encode, decode } from '@metamask/abi-utils'; + * + * const types = ['uint256', 'string']; + * const encoded = encode(types, [42, 'Hello, world!']); + * const decoded = decode(types, encoded); + * + * console.log(decoded); // [42n, 'Hello, world!'] + * ``` + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html + * @param types - The types to encode. + * @param values - The values to encode. This array must have the same length as + * the types array. + * @param packed - Whether to use the non-standard packed mode. Defaults to + * `false`. + * @param tight - Whether to pack the values tightly. When enabled, the values + * will be packed without any padding. This matches the behaviour of + * `ethereumjs-abi`. Defaults to `false`. + * @returns The ABI encoded bytes. + */ +const encode = (types, values, packed, tight) => { + try { + return (0, packer_1.pack)({ types, values, packed, tight }); + } + catch (error) { + if (error instanceof errors_1.ParserError) { + throw new errors_1.ParserError(`Unable to encode value: ${error.message}`, error); + } + throw new errors_1.ParserError(`An unexpected error occurred: ${(0, errors_1.getErrorMessage)(error)}`, error); + } +}; +exports.encode = encode; +/** + * Encode the data with the provided type. The type must be a valid Solidity + * ABI type. + * + * See {@link encode} for more information on how values are parsed. + * + * @example + * ```typescript + * import { encodeSingle, decodeSingle } from '@metamask/abi-utils'; + * + * const encoded = encodeSingle('uint256', 42); + * const decoded = decodeSingle('uint256', encoded); + * + * console.log(decoded); // 42n + * ``` + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#types + * @param type - The type to encode. + * @param value - The value to encode. + * @returns The ABI encoded bytes. + */ +const encodeSingle = (type, value) => { + return (0, exports.encode)([type], [value]); +}; +exports.encodeSingle = encodeSingle; +/** + * Encode the data with the provided types. The types must be valid Solidity + * ABI types. This is similar to {@link encode}, but the values are encoded in + * the non-standard packed mode. This differs from the standard encoding in the + * following ways: + * + * - Most values are packed tightly, without alignment padding. + * - The exception is array values, which are padded to 32 bytes. + * - Values are still padded to their full size, i.e., `uint16` values are still + * padded to 2 bytes, regardless of the length of the value. + * - The encoding of dynamic types (`bytes`, `string`) is different. The length + * of the dynamic type is not included in the encoding, and the dynamic type is + * not padded to a multiple of 32 bytes. + * - All values are encoded in-place, without any offsets. + * + * The encoding of this is ambiguous as soon as there is more than one dynamic + * type. That means that these values cannot be decoded with {@link decode} or + * Solidity's `abi.decode` function. + * + * See {@link encode} for more information on how values are parsed. + * + * @example + * ```typescript + * import { encodePacked } from '@metamask/abi-utils'; + * + * const encoded = encodePacked(['uint8'], [42]); + * + * console.log(encoded); // `Uint8Array [ 42 ]` + * ``` + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#types + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#non-standard-packed-mode + * @param types - The types to encode. + * @param values - The values to encode. + * @param tight - Whether to pack the values tightly. When enabled, `bytesN` + * values in arrays will be packed without any padding. This matches the + * behaviour of `ethereumjs-abi`. Defaults to `false`. + * @returns The ABI encoded bytes. + */ +const encodePacked = (types, values, tight) => { + return (0, exports.encode)(types, values, true, tight); +}; +exports.encodePacked = encodePacked; +/** + * Decode an ABI encoded buffer with the specified types. The types must be + * valid Solidity ABI types. + * + * This will attempt to infer the output types from the input types. For + * example, if you use `uint256` as an input type, the output type will be + * `bigint`. This does not work for all types, however. For example, if you use + * nested array types or tuple types, the output type will be `unknown`. + * + * The resulting types of the values will be as follows: + * + * | Contract ABI Type | Resulting JavaScript Type | + * | ----------------- | ------------------------- | + * | `address` | `string` | + * | `bool` | `boolean` | + * | `bytes(n)` | `Uint8Array` | + * | `function` | {@link SolidityFunction} | + * | `int(n)` | `bigint` | + * | `string` | `string` | + * | `tuple` | `Array` | + * | `array` | `Array` | + * | `uint(n)` | `bigint` | + * + * @example + * ```typescript + * import { encode, decode } from '@metamask/abi-utils'; + * + * const types = ['uint256', 'string']; + * const encoded = encode(types, [42, 'Hello, world!']); + * const decoded = decode(types, encoded); + * + * console.log(decoded); // [42n, 'Hello, world!'] + * ``` + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#types + * @param types - The types to decode the bytes with. + * @param value - The bytes-like value to decode. + * @returns The decoded values as array. + */ +const decode = (types, value) => { + const bytes = (0, utils_1.createBytes)(value); + try { + return (0, packer_1.unpack)(types, bytes); + } + catch (error) { + if (error instanceof errors_1.ParserError) { + throw new errors_1.ParserError(`Unable to decode value: ${error.message}`, error); + } + throw new errors_1.ParserError(`An unexpected error occurred: ${(0, errors_1.getErrorMessage)(error)}`, error); + } +}; +exports.decode = decode; +/** + * Decode the data with the provided type. The type must be a valid Solidity + * ABI type. + * + * See {@link decode} for more information on how values are parsed. + * + * @example + * ```typescript + * import { encodeSingle, decodeSingle } from '@metamask/abi-utils'; + * + * const encoded = encodeSingle('uint256', 42); + * const decoded = decodeSingle('uint256', encoded); + * + * console.log(decoded); // 42n + * ``` + * @see https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#types + * @param type - The type to decode. + * @param value - The bytes-like value to decode. + * @returns The decoded value. + */ +const decodeSingle = (type, value) => { + const result = (0, exports.decode)([type], value); + (0, utils_1.assert)(result.length === 1, new errors_1.ParserError('Decoded value array has unexpected length.')); + return result[0]; +}; +exports.decodeSingle = decodeSingle; +//# sourceMappingURL=abi.js.map + +/***/ }), + +/***/ 5961: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ParserError = exports.getErrorStack = exports.getErrorMessage = void 0; +const utils_1 = __webpack_require__(22049); +/** + * Attempt to get an error message from a value. + * + * - If the value is an error, the error's message is returned. + * - If the value is an object with a `message` property, the value of that + * property is returned. + * - If the value is a string, the value is returned. + * - Otherwise, "Unknown error." is returned. + * + * @param error - The value to get an error message from. + * @returns The error message. + * @internal + */ +const getErrorMessage = (error) => { + if (typeof error === 'string') { + return error; + } + if (error instanceof Error) { + return error.message; + } + if ((0, utils_1.isObject)(error) && + (0, utils_1.hasProperty)(error, 'message') && + typeof error.message === 'string') { + return error.message; + } + return 'Unknown error.'; +}; +exports.getErrorMessage = getErrorMessage; +/** + * Get the error stack from a value. If the value is an error, the error's stack + * is returned. Otherwise, it returns `undefined`. + * + * @param error - The value to get an error stack from. + * @returns The error stack, or `undefined` if the value is not an error. + * @internal + */ +const getErrorStack = (error) => { + if (error instanceof Error) { + return error.stack; + } + return undefined; +}; +exports.getErrorStack = getErrorStack; +/** + * An error that is thrown when the ABI encoder or decoder encounters an + * issue. + */ +class ParserError extends Error { + constructor(message, originalError) { + super(message); + this.name = 'ParserError'; + const originalStack = (0, exports.getErrorStack)(originalError); + if (originalStack) { + this.stack = originalStack; + } + } +} +exports.ParserError = ParserError; +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 93256: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(56498), exports); +__exportStar(__webpack_require__(5961), exports); +__exportStar(__webpack_require__(11126), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 57924: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.iterate = void 0; +const utils_1 = __webpack_require__(22049); +/** + * Iterate over a buffer with the specified size. This will yield a part of the + * buffer starting at an increment of the specified size, until the end of the + * buffer is reached. + * + * Calling the `skip` function will make it skip the specified number of bytes. + * + * @param buffer - The buffer to iterate over. + * @param size - The number of bytes to iterate with. + * @returns An iterator that yields the parts of the byte array. + * @yields The parts of the byte array. + */ +const iterate = function* (buffer, size = 32) { + for (let pointer = 0; pointer < buffer.length; pointer += size) { + const skip = (length) => { + (0, utils_1.assert)(length >= 0, 'Cannot skip a negative number of bytes.'); + (0, utils_1.assert)(length % size === 0, 'Length must be a multiple of the size.'); + pointer += length; + }; + const value = buffer.subarray(pointer); + yield { skip, value }; + } + return { + skip: () => undefined, + value: new Uint8Array(), + }; +}; +exports.iterate = iterate; +//# sourceMappingURL=iterator.js.map + +/***/ }), + +/***/ 37700: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unpack = exports.pack = exports.isDynamicParser = exports.getParser = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const iterator_1 = __webpack_require__(57924); +const parsers_1 = __webpack_require__(46207); +const utils_2 = __webpack_require__(26365); +/** + * Get the parser for the specified type. + * + * @param type - The type to get a parser for. + * @returns The parser. + * @throws If there is no parser for the specified type. + */ +const getParser = (type) => { + const parsers = { + address: parsers_1.address, + array: parsers_1.array, + bool: parsers_1.bool, + bytes: parsers_1.bytes, + fixedBytes: parsers_1.fixedBytes, + function: parsers_1.fn, + number: parsers_1.number, + string: parsers_1.string, + tuple: parsers_1.tuple, + }; + const staticParser = parsers[type]; + if (staticParser) { + return staticParser; + } + const parser = Object.values(parsers).find((value) => value.isType(type)); + if (parser) { + return parser; + } + throw new errors_1.ParserError(`The type "${type}" is not supported.`); +}; +exports.getParser = getParser; +/** + * Check if the specified parser is dynamic, for the provided types. This is + * primarily used for parsing tuples, where a tuple can be dynamic based on the + * types. For other parsers, it will simply use the set `isDynamic` value. + * + * @param parser - The parser to check. + * @param type - The type to check the parser with. + * @returns Whether the parser is dynamic. + */ +const isDynamicParser = (parser, type) => { + const { isDynamic } = parser; + if (typeof isDynamic === 'function') { + return isDynamic(type); + } + return isDynamic; +}; +exports.isDynamicParser = isDynamicParser; +/** + * Pack the provided values in a buffer, encoded with the specified types. If a + * buffer is specified, the resulting value will be concatenated with the + * buffer. + * + * @param args - The arguments object. + * @param args.types - The types of the values to pack. + * @param args.values - The values to pack. + * @param args.packed - Whether to use the non-standard packed mode. Defaults to + * `false`. + * @param args.arrayPacked - Whether to use the non-standard packed mode for + * arrays. Defaults to `false`. + * @param args.byteArray - The byte array to encode the values into. Defaults to + * an empty array. + * @param args.tight - Whether to use tight packing mode. Only applicable when + * `packed` is true. When true, the packed mode will not add any padding bytes. + * This matches the packing behaviour of `ethereumjs-abi`, but is not standard. + * @returns The resulting encoded buffer. + */ +const pack = ({ types, values, packed = false, tight = false, arrayPacked = false, byteArray = new Uint8Array(), }) => { + (0, utils_1.assert)(types.length === values.length, new errors_1.ParserError(`The number of types (${types.length}) does not match the number of values (${values.length}).`)); + const { staticBuffer, dynamicBuffer, pointers } = types.reduce( + // eslint-disable-next-line @typescript-eslint/no-shadow + ({ staticBuffer, dynamicBuffer, pointers }, type, index) => { + const parser = (0, exports.getParser)(type); + const value = values[index]; + // If packed mode is enabled, we can skip the dynamic check, as all + // values are encoded in the static buffer. + if (packed || arrayPacked || !(0, exports.isDynamicParser)(parser, type)) { + return { + staticBuffer: parser.encode({ + buffer: staticBuffer, + value, + type, + packed, + tight, + }), + dynamicBuffer, + pointers, + }; + } + const newStaticBuffer = (0, utils_1.concatBytes)([staticBuffer, new Uint8Array(32)]); + const newDynamicBuffer = parser.encode({ + buffer: dynamicBuffer, + value, + type, + packed, + tight, + }); + return { + staticBuffer: newStaticBuffer, + dynamicBuffer: newDynamicBuffer, + pointers: [ + ...pointers, + { position: staticBuffer.length, pointer: dynamicBuffer.length }, + ], + }; + }, { + staticBuffer: new Uint8Array(), + dynamicBuffer: new Uint8Array(), + pointers: [], + }); + // If packed mode is enabled, there shouldn't be any dynamic values. + (0, utils_1.assert)((!packed && !arrayPacked) || dynamicBuffer.length === 0, new errors_1.ParserError('Invalid pack state.')); + const dynamicStart = staticBuffer.length; + const updatedBuffer = pointers.reduce((target, { pointer, position }) => { + const offset = (0, utils_2.padStart)((0, utils_1.numberToBytes)(dynamicStart + pointer)); + return (0, utils_2.set)(target, offset, position); + }, staticBuffer); + return (0, utils_1.concatBytes)([byteArray, updatedBuffer, dynamicBuffer]); +}; +exports.pack = pack; +const unpack = (types, buffer) => { + const iterator = (0, iterator_1.iterate)(buffer); + return types.map((type) => { + const { value: { value, skip }, done, } = iterator.next(); + (0, utils_1.assert)(!done, new errors_1.ParserError(`The encoded value is invalid for the provided types. Reached end of buffer while attempting to parse "${type}".`)); + const parser = (0, exports.getParser)(type); + const isDynamic = (0, exports.isDynamicParser)(parser, type); + if (isDynamic) { + const pointer = (0, utils_1.bytesToNumber)(value.subarray(0, 32)); + const target = buffer.subarray(pointer); + return parser.decode({ type, value: target, skip }); + } + return parser.decode({ type, value, skip }); + }); +}; +exports.unpack = unpack; +//# sourceMappingURL=packer.js.map + +/***/ }), + +/***/ 91563: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.address = exports.getAddress = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const utils_2 = __webpack_require__(26365); +/** + * Normalize an address value. This accepts the address as: + * + * - A hex string starting with the `0x` prefix. + * - A byte array (`Uint8Array` or `Buffer`). + * + * It checks that the address is 20 bytes long. + * + * @param value - The value to normalize. + * @returns The normalized address as `Uint8Array`. + */ +const getAddress = (value) => { + const bytesValue = (0, utils_1.createBytes)(value); + (0, utils_1.assert)(bytesValue.length <= 20, new errors_1.ParserError(`Invalid address value. Expected address to be 20 bytes long, but received ${bytesValue.length} bytes.`)); + return (0, utils_2.padStart)(bytesValue, 20); +}; +exports.getAddress = getAddress; +exports.address = { + isDynamic: false, + /** + * Get if the given value is a valid address type. Since `address` is a simple + * type, this is just a check that the value is "address". + * + * @param type - The type to check. + * @returns Whether the type is a valid address type. + */ + isType: (type) => type === 'address', + /** + * Get the byte length of an encoded address. Since `address` is a simple + * type, this always returns 32. + * + * Note that actual addresses are only 20 bytes long, but the encoding of + * the `address` type is always 32 bytes long. + * + * @returns The byte length of an encoded address. + */ + getByteLength() { + return 32; + }, + /** + * Encode the given address to a 32-byte-long byte array. + * + * @param args - The encoding arguments. + * @param args.buffer - The byte array to add to. + * @param args.value - The address to encode. + * @param args.packed - Whether to use packed encoding. + * @returns The bytes with the encoded address added to it. + */ + encode({ buffer, value, packed }) { + const addressValue = (0, exports.getAddress)(value); + // If we're using packed encoding, we can just add the address bytes to the + // byte array, without adding any padding. + if (packed) { + return (0, utils_1.concatBytes)([buffer, addressValue]); + } + const addressBuffer = (0, utils_2.padStart)(addressValue); + return (0, utils_1.concatBytes)([buffer, addressBuffer]); + }, + /** + * Decode the given byte array to an address. + * + * @param args - The decoding arguments. + * @param args.value - The byte array to decode. + * @returns The decoded address as a hexadecimal string, starting with the + * "0x"-prefix. + */ + decode({ value }) { + return (0, utils_1.add0x)((0, utils_1.bytesToHex)(value.slice(12, 32))); + }, +}; +//# sourceMappingURL=address.js.map + +/***/ }), + +/***/ 186: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.array = exports.getTupleType = exports.getArrayType = exports.isArrayType = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const packer_1 = __webpack_require__(37700); +const utils_2 = __webpack_require__(26365); +const fixed_bytes_1 = __webpack_require__(83415); +const tuple_1 = __webpack_require__(30717); +const ARRAY_REGEX = /^(?.*)\[(?\d*?)\]$/u; +const isArrayType = (type) => ARRAY_REGEX.test(type); +exports.isArrayType = isArrayType; +/** + * Get the type of the array. + * + * @param type - The type to get the array type for. + * @returns The array type. + */ +const getArrayType = (type) => { + const match = type.match(ARRAY_REGEX); + (0, utils_1.assert)(match?.groups?.type, new errors_1.ParserError(`Invalid array type. Expected an array type, but received "${type}".`)); + return [ + match.groups.type, + match.groups.length ? parseInt(match.groups.length, 10) : undefined, + ]; +}; +exports.getArrayType = getArrayType; +/** + * Get the type of the array as a tuple type. This is used for encoding fixed + * length arrays, which are encoded as tuples. + * + * @param innerType - The type of the array. + * @param length - The length of the array. + * @returns The tuple type. + */ +const getTupleType = (innerType, length) => { + return `(${new Array(length).fill(innerType).join(',')})`; +}; +exports.getTupleType = getTupleType; +exports.array = { + /** + * Check if the array is dynamic. Arrays are dynamic if the array does not + * have a fixed length, or if the array type is dynamic. + * + * @param type - The type to check. + * @returns Whether the array is dynamic. + */ + isDynamic(type) { + const [innerType, length] = (0, exports.getArrayType)(type); + return ( + // `T[]` is dynamic for any `T`. `T[k]` is dynamic for any dynamic `T` and + // any `k >= 0`. + length === undefined || (0, packer_1.isDynamicParser)((0, packer_1.getParser)(innerType), innerType)); + }, + /** + * Check if a type is an array type. + * + * @param type - The type to check. + * @returns Whether the type is an array type. + */ + isType(type) { + return (0, exports.isArrayType)(type); + }, + /** + * Get the byte length of an encoded array. If the array is dynamic, this + * returns 32, i.e., the length of the pointer to the array. If the array is + * static, this returns the byte length of the resulting tuple type. + * + * @param type - The type to get the byte length for. + * @returns The byte length of an encoded array. + */ + getByteLength(type) { + (0, utils_1.assert)((0, exports.isArrayType)(type), new errors_1.ParserError(`Expected an array type, but received "${type}".`)); + const [innerType, length] = (0, exports.getArrayType)(type); + if (!(0, packer_1.isDynamicParser)(this, type) && length !== undefined) { + return tuple_1.tuple.getByteLength((0, exports.getTupleType)(innerType, length)); + } + return 32; + }, + /** + * Encode the given array to a byte array. If the array is static, this uses + * the tuple encoder. + * + * @param args - The encoding arguments. + * @param args.type - The type of the array. + * @param args.buffer - The byte array to add to. + * @param args.value - The array to encode. + * @param args.packed - Whether to use non-standard packed encoding. + * @param args.tight - Whether to use non-standard tight encoding. + * @returns The bytes with the encoded array added to it. + */ + encode({ type, buffer, value, packed, tight }) { + const [arrayType, fixedLength] = (0, exports.getArrayType)(type); + // Packed encoding does not support nested arrays. + (0, utils_1.assert)(!packed || !(0, exports.isArrayType)(arrayType), new errors_1.ParserError(`Cannot pack nested arrays.`)); + // Tightly pack `T[]` where `T` is a dynamic type. This is not supported in + // Solidity, but is commonly used in the Ethereum ecosystem. + if (packed && (0, packer_1.isDynamicParser)((0, packer_1.getParser)(arrayType), arrayType)) { + return (0, packer_1.pack)({ + types: new Array(value.length).fill(arrayType), + values: value, + byteArray: buffer, + packed, + arrayPacked: true, + tight, + }); + } + if (fixedLength) { + (0, utils_1.assert)(fixedLength === value.length, new errors_1.ParserError(`Array length does not match type length. Expected a length of ${fixedLength}, but received ${value.length}.`)); + // `T[k]` for any `T` and `k` is encoded as `(T[0], ..., T[k - 1])`. + return tuple_1.tuple.encode({ + type: (0, exports.getTupleType)(arrayType, fixedLength), + buffer, + value, + // In "tight" mode, we don't pad the values to 32 bytes if the value is + // of type `bytesN`. This is an edge case in `ethereumjs-abi` that we + // support to provide compatibility with it. + packed: fixed_bytes_1.fixedBytes.isType(arrayType) && tight, + tight, + }); + } + // For packed encoding, we don't need to encode the length of the array, + // so we can just encode the values. + if (packed) { + return (0, packer_1.pack)({ + types: new Array(value.length).fill(arrayType), + values: value, + byteArray: buffer, + // In "tight" mode, we don't pad the values to 32 bytes if the value is + // of type `bytesN`. This is an edge case in `ethereumjs-abi` that we + // support to provide compatibility with it. + packed: fixed_bytes_1.fixedBytes.isType(arrayType) && tight, + arrayPacked: true, + tight, + }); + } + // `T[]` with `k` elements is encoded as `k (T[0], ..., T[k - 1])`. That + // means that we just need to encode the length of the array, and then the + // array itself. The pointer is encoded by the {@link pack} function. + const arrayLength = (0, utils_2.padStart)((0, utils_1.numberToBytes)(value.length)); + return (0, packer_1.pack)({ + types: new Array(value.length).fill(arrayType), + values: value, + byteArray: (0, utils_1.concatBytes)([buffer, arrayLength]), + packed, + tight, + }); + }, + /** + * Decode an array from the given byte array. + * + * @param args - The decoding arguments. + * @param args.type - The type of the array. + * @param args.value - The byte array to decode. + * @returns The decoded array. + */ + decode({ type, value, ...rest }) { + const [arrayType, fixedLength] = (0, exports.getArrayType)(type); + if (fixedLength) { + const result = tuple_1.tuple.decode({ + type: (0, exports.getTupleType)(arrayType, fixedLength), + value, + ...rest, + }); + (0, utils_1.assert)(result.length === fixedLength, new errors_1.ParserError(`Array length does not match type length. Expected a length of ${fixedLength}, but received ${result.length}.`)); + return result; + } + const arrayLength = (0, utils_1.bytesToNumber)(value.subarray(0, 32)); + return (0, packer_1.unpack)(new Array(arrayLength).fill(arrayType), value.subarray(32)); + }, +}; +//# sourceMappingURL=array.js.map + +/***/ }), + +/***/ 47435: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bool = exports.getBooleanValue = void 0; +const utils_1 = __webpack_require__(22049); +const superstruct_1 = __webpack_require__(2150); +const errors_1 = __webpack_require__(5961); +const number_1 = __webpack_require__(6150); +const BooleanCoercer = (0, superstruct_1.coerce)((0, superstruct_1.boolean)(), (0, superstruct_1.union)([(0, superstruct_1.literal)('true'), (0, superstruct_1.literal)('false')]), (value) => value === 'true'); +/** + * Normalize a boolean value. This accepts the boolean as: + * + * - A boolean literal. + * - The string "true" or "false". + * + * @param value - The value to get a boolean for. + * @returns The parsed boolean value. This is `BigInt(1)` for truthy values, or + * `BigInt(0)` for falsy values. + */ +const getBooleanValue = (value) => { + try { + const booleanValue = (0, superstruct_1.create)(value, BooleanCoercer); + if (booleanValue) { + return BigInt(1); + } + return BigInt(0); + } + catch { + throw new errors_1.ParserError(`Invalid boolean value. Expected a boolean literal, or the string "true" or "false", but received "${value}".`); + } +}; +exports.getBooleanValue = getBooleanValue; +exports.bool = { + isDynamic: false, + /** + * Get if the given value is a valid boolean type. Since `bool` is a simple + * type, this is just a check that the value is "bool". + * + * @param type - The type to check. + * @returns Whether the type is a valid boolean type. + */ + isType: (type) => type === 'bool', + /** + * Get the byte length of an encoded boolean. Since `bool` is a simple + * type, this always returns 32. + * + * Note that actual booleans are only 1 byte long, but the encoding of + * the `bool` type is always 32 bytes long. + * + * @returns The byte length of an encoded boolean. + */ + getByteLength() { + return 32; + }, + /** + * Encode the given boolean to a byte array. + * + * @param args - The encoding arguments. + * @param args.buffer - The byte array to add to. + * @param args.value - The boolean to encode. + * @param args.packed - Whether the value is packed. + * @param args.tight - Whether to use non-standard tight encoding. + * @returns The bytes with the encoded boolean added to it. + */ + encode({ buffer, value, packed, tight }) { + const booleanValue = (0, exports.getBooleanValue)(value); + // For packed encoding, we add a single byte (`0x00` or `0x01`) to the byte + // array. + if (packed) { + return (0, utils_1.concatBytes)([buffer, (0, utils_1.bigIntToBytes)(booleanValue)]); + } + // Booleans are encoded as 32-byte integers, so we use the number parser + // to encode the boolean value. + return number_1.number.encode({ + type: 'uint256', + buffer, + value: booleanValue, + packed, + tight, + }); + }, + /** + * Decode the given byte array to a boolean. + * + * @param args - The decoding arguments. + * @returns The decoded boolean. + */ + decode(args) { + // Booleans are encoded as 32-byte integers, so we use the number parser + // to decode the boolean value. + return number_1.number.decode({ ...args, type: 'uint256' }) === BigInt(1); + }, +}; +//# sourceMappingURL=bool.js.map + +/***/ }), + +/***/ 99356: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bytes = void 0; +const utils_1 = __webpack_require__(22049); +const utils_2 = __webpack_require__(26365); +exports.bytes = { + isDynamic: true, + /** + * Check if a type is a bytes type. Since `bytes` is a simple type, this is + * just a check that the type is "bytes". + * + * @param type - The type to check. + * @returns Whether the type is a bytes type. + */ + isType: (type) => type === 'bytes', + /** + * Get the byte length of an encoded bytes value. Since `bytes` is a simple + * type, this always returns 32. + * + * Note that actual length of a bytes value is variable, but the encoded + * static value (pointer) is always 32 bytes long. + * + * @returns The byte length of an encoded bytes value. + */ + getByteLength() { + return 32; + }, + /** + * Encode the given bytes value to a byte array. + * + * @param args - The encoding arguments. + * @param args.buffer - The byte array to add to. + * @param args.value - The bytes value to encode. + * @param args.packed - Whether to use packed encoding. + * @returns The bytes with the encoded bytes value added to it. + */ + encode({ buffer, value, packed }) { + const bufferValue = (0, utils_1.createBytes)(value); + // For packed encoding, we can just add the bytes value to the byte array, + // without adding any padding or alignment. There is also no need to + // encode the length of the bytes. + if (packed) { + return (0, utils_1.concatBytes)([buffer, bufferValue]); + } + const paddedSize = Math.ceil(bufferValue.byteLength / 32) * 32; + // Bytes of length `k` are encoded as `k pad_right(bytes)`. + return (0, utils_1.concatBytes)([ + buffer, + (0, utils_2.padStart)((0, utils_1.numberToBytes)(bufferValue.byteLength)), + (0, utils_2.padEnd)(bufferValue, paddedSize), + ]); + }, + /** + * Decode the given byte array to a bytes value. + * + * @param args - The decoding arguments. + * @param args.value - The byte array to decode. + * @returns The decoded bytes value as a `Uint8Array`. + */ + decode({ value }) { + const bytesValue = value.subarray(0, 32); + const length = (0, utils_1.bytesToNumber)(bytesValue); + // Since we're returning a `Uint8Array`, we use `slice` to copy the bytes + // into a new array. + return value.slice(32, 32 + length); + }, +}; +//# sourceMappingURL=bytes.js.map + +/***/ }), + +/***/ 83415: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fixedBytes = exports.getByteLength = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const utils_2 = __webpack_require__(26365); +const BYTES_REGEX = /^bytes([0-9]{1,2})$/u; +/** + * Get the length of the specified type. If a length is not specified, or if the + * length is out of range (0 < n <= 32), this will throw an error. + * + * @param type - The type to get the length for. + * @returns The byte length of the type. + */ +const getByteLength = (type) => { + const bytes = type.match(BYTES_REGEX)?.[1]; + (0, utils_1.assert)(bytes, `Invalid byte length. Expected a number between 1 and 32, but received "${type}".`); + const length = Number(bytes); + (0, utils_1.assert)(length > 0 && length <= 32, new errors_1.ParserError(`Invalid byte length. Expected a number between 1 and 32, but received "${type}".`)); + return length; +}; +exports.getByteLength = getByteLength; +exports.fixedBytes = { + isDynamic: false, + /** + * Check if a type is a fixed bytes type. + * + * @param type - The type to check. + * @returns Whether the type is a fixed bytes type. + */ + isType(type) { + return BYTES_REGEX.test(type); + }, + /** + * Get the byte length of an encoded fixed bytes type. + * + * @returns The byte length of the type. + */ + getByteLength() { + return 32; + }, + /** + * Encode a fixed bytes value. + * + * @param args - The arguments to encode. + * @param args.type - The type of the value. + * @param args.buffer - The byte array to add to. + * @param args.value - The value to encode. + * @param args.packed - Whether to use packed encoding. + * @returns The bytes with the encoded value added to it. + */ + encode({ type, buffer, value, packed }) { + const length = (0, exports.getByteLength)(type); + const bufferValue = (0, utils_1.createBytes)(value); + (0, utils_1.assert)(bufferValue.length <= length, new errors_1.ParserError(`Expected a value of length ${length}, but received a value of length ${bufferValue.length}.`)); + // For packed encoding, the value is padded to the length of the type, and + // then added to the byte array. + if (packed) { + return (0, utils_1.concatBytes)([buffer, (0, utils_2.padEnd)(bufferValue, length)]); + } + return (0, utils_1.concatBytes)([buffer, (0, utils_2.padEnd)(bufferValue)]); + }, + /** + * Decode a fixed bytes value. + * + * @param args - The arguments to decode. + * @param args.type - The type of the value. + * @param args.value - The value to decode. + * @returns The decoded value as a `Uint8Array`. + */ + decode({ type, value }) { + const length = (0, exports.getByteLength)(type); + // Since we're returning a `Uint8Array`, we use `slice` to copy the bytes + // into a new array. + return value.slice(0, length); + }, +}; +//# sourceMappingURL=fixed-bytes.js.map + +/***/ }), + +/***/ 27827: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fn = exports.getFunction = void 0; +const utils_1 = __webpack_require__(22049); +const superstruct_1 = __webpack_require__(2150); +const errors_1 = __webpack_require__(5961); +const fixed_bytes_1 = __webpack_require__(83415); +/** + * A struct that represents a Solidity function. The value must be a hex string + * or a byte array. The created value will always be an object with an `address` + * and `selector` property. + */ +const FunctionStruct = (0, superstruct_1.coerce)((0, superstruct_1.object)({ + address: utils_1.StrictHexStruct, + selector: utils_1.StrictHexStruct, +}), (0, superstruct_1.union)([utils_1.StrictHexStruct, (0, superstruct_1.instance)(Uint8Array)]), (value) => { + const bytes = (0, utils_1.createBytes)(value); + (0, utils_1.assert)(bytes.length === 24, new errors_1.ParserError(`Invalid Solidity function. Expected function to be 24 bytes long, but received ${bytes.length} bytes.`)); + return { + address: (0, utils_1.bytesToHex)(bytes.subarray(0, 20)), + selector: (0, utils_1.bytesToHex)(bytes.subarray(20, 24)), + }; +}); +/** + * Normalize a function. This accepts the function as: + * + * - A {@link SolidityFunction} object. + * - A hexadecimal string. + * - A byte array. + * + * @param input - The function-like input. + * @returns The function as buffer. + */ +const getFunction = (input) => { + const value = (0, superstruct_1.create)(input, FunctionStruct); + return (0, utils_1.concatBytes)([(0, utils_1.hexToBytes)(value.address), (0, utils_1.hexToBytes)(value.selector)]); +}; +exports.getFunction = getFunction; +exports.fn = { + isDynamic: false, + /** + * Check if a type is a function type. Since `function` is a simple type, this + * is just a check that the type is "function". + * + * @param type - The type to check. + * @returns Whether the type is a function type. + */ + isType: (type) => type === 'function', + /** + * Get the byte length of an encoded function. Since `function` is a simple + * type, this always returns 32. + * + * Note that actual functions are only 24 bytes long, but the encoding of + * the `function` type is always 32 bytes long. + * + * @returns The byte length of an encoded function. + */ + getByteLength() { + return 32; + }, + /** + * Encode the given function to a byte array. + * + * @param args - The encoding arguments. + * @param args.buffer - The byte array to add to. + * @param args.value - The function to encode. + * @param args.packed - Whether to use packed encoding. + * @param args.tight - Whether to use non-standard tight encoding. + * @returns The bytes with the encoded function added to it. + */ + encode({ buffer, value, packed, tight }) { + const fnValue = (0, exports.getFunction)(value); + // Functions are encoded as `bytes24`, so we use the fixedBytes parser to + // encode the function. + return fixed_bytes_1.fixedBytes.encode({ + type: 'bytes24', + buffer, + value: fnValue, + packed, + tight, + }); + }, + /** + * Decode the given byte array to a function. + * + * @param args - The decoding arguments. + * @param args.value - The byte array to decode. + * @returns The decoded function as a {@link SolidityFunction} object. + */ + decode({ value }) { + return { + address: (0, utils_1.bytesToHex)(value.slice(0, 20)), + selector: (0, utils_1.bytesToHex)(value.slice(20, 24)), + }; + }, +}; +//# sourceMappingURL=function.js.map + +/***/ }), + +/***/ 46207: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(91563), exports); +__exportStar(__webpack_require__(186), exports); +__exportStar(__webpack_require__(47435), exports); +__exportStar(__webpack_require__(99356), exports); +__exportStar(__webpack_require__(83415), exports); +__exportStar(__webpack_require__(27827), exports); +__exportStar(__webpack_require__(6150), exports); +__exportStar(__webpack_require__(28160), exports); +__exportStar(__webpack_require__(8446), exports); +__exportStar(__webpack_require__(30717), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 6150: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.number = exports.getBigInt = exports.assertNumberLength = exports.getLength = exports.isSigned = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const utils_2 = __webpack_require__(26365); +const NUMBER_REGEX = /^u?int(?[0-9]*)?$/u; +/** + * Check if a number type is signed. + * + * @param type - The type to check. + * @returns Whether the type is signed. + */ +const isSigned = (type) => { + return !type.startsWith('u'); +}; +exports.isSigned = isSigned; +/** + * Get the length of the specified type. If a length is not specified, if the + * length is out of range (8 <= n <= 256), or if the length is not a multiple of + * 8, this will throw an error. + * + * @param type - The type to get the length for. + * @returns The bit length of the type. + */ +const getLength = (type) => { + if (type === 'int' || type === 'uint') { + return 256; + } + const match = type.match(NUMBER_REGEX); + (0, utils_1.assert)(match?.groups?.length, new errors_1.ParserError(`Invalid number type. Expected a number type, but received "${type}".`)); + const length = parseInt(match.groups.length, 10); + (0, utils_1.assert)(length >= 8 && length <= 256, new errors_1.ParserError(`Invalid number length. Expected a number between 8 and 256, but received "${type}".`)); + (0, utils_1.assert)(length % 8 === 0, new errors_1.ParserError(`Invalid number length. Expected a multiple of 8, but received "${type}".`)); + return length; +}; +exports.getLength = getLength; +/** + * Assert that the byte length of the given value is in range for the given + * number type. + * + * @param value - The value to check. + * @param type - The type of the value. + * @throws If the value is out of range for the type. + */ +const assertNumberLength = (value, type) => { + const length = (0, exports.getLength)(type); + const maxValue = BigInt(2) ** BigInt(length - ((0, exports.isSigned)(type) ? 1 : 0)) - BigInt(1); + if ((0, exports.isSigned)(type)) { + // Signed types must be in the range of `-(2^(length - 1))` to + // `2^(length - 1) - 1`. + (0, utils_1.assert)(value >= -(maxValue + BigInt(1)) && value <= maxValue, new errors_1.ParserError(`Number "${value}" is out of range for type "${type}".`)); + return; + } + // Unsigned types must be in the range of `0` to `2^length - 1`. + (0, utils_1.assert)(value <= maxValue, new errors_1.ParserError(`Number "${value}" is out of range for type "${type}".`)); +}; +exports.assertNumberLength = assertNumberLength; +/** + * Normalize a `bigint` value. This accepts the value as: + * + * - A `bigint`. + * - A `number`. + * - A decimal string, i.e., a string that does not start with "0x". + * - A hexadecimal string, i.e., a string that starts with "0x". + * + * @param value - The number-like value to parse. + * @returns The value parsed as bigint. + */ +const getBigInt = (value) => { + try { + return (0, utils_1.createBigInt)(value); + } + catch { + throw new errors_1.ParserError(`Invalid number. Expected a valid number value, but received "${value}".`); + } +}; +exports.getBigInt = getBigInt; +exports.number = { + isDynamic: false, + /** + * Check if a type is a number type. + * + * @param type - The type to check. + * @returns Whether the type is a number type. + */ + isType(type) { + return NUMBER_REGEX.test(type); + }, + /** + * Get the byte length of an encoded number type. Since `int` and `uint` are + * simple types, this will always return 32. + * + * @returns The byte length of the type. + */ + getByteLength() { + return 32; + }, + /** + * Encode a number value. + * + * @param args - The arguments to encode. + * @param args.type - The type of the value. + * @param args.buffer - The byte array to add to. + * @param args.value - The value to encode. + * @param args.packed - Whether to use packed encoding. + * @returns The bytes with the encoded value added to it. + */ + encode({ type, buffer, value, packed }) { + const bigIntValue = (0, exports.getBigInt)(value); + (0, exports.assertNumberLength)(bigIntValue, type); + if ((0, exports.isSigned)(type)) { + // For packed encoding, the value is padded to the length of the type, and + // then added to the byte array. + if (packed) { + const length = (0, exports.getLength)(type) / 8; + return (0, utils_1.concatBytes)([buffer, (0, utils_1.signedBigIntToBytes)(bigIntValue, length)]); + } + return (0, utils_1.concatBytes)([ + buffer, + (0, utils_2.padStart)((0, utils_1.signedBigIntToBytes)(bigIntValue, 32)), + ]); + } + // For packed encoding, the value is padded to the length of the type, and + // then added to the byte array. + if (packed) { + const length = (0, exports.getLength)(type) / 8; + return (0, utils_1.concatBytes)([ + buffer, + (0, utils_2.padStart)((0, utils_1.bigIntToBytes)(bigIntValue), length), + ]); + } + return (0, utils_1.concatBytes)([buffer, (0, utils_2.padStart)((0, utils_1.bigIntToBytes)(bigIntValue))]); + }, + /** + * Decode a number value. + * + * @param args - The decoding arguments. + * @param args.type - The type of the value. + * @param args.value - The value to decode. + * @returns The decoded value. + */ + decode({ type, value }) { + const buffer = value.subarray(0, 32); + if ((0, exports.isSigned)(type)) { + const numberValue = (0, utils_1.bytesToSignedBigInt)(buffer); + (0, exports.assertNumberLength)(numberValue, type); + return numberValue; + } + const numberValue = (0, utils_1.bytesToBigInt)(buffer); + (0, exports.assertNumberLength)(numberValue, type); + return numberValue; + }, +}; +//# sourceMappingURL=number.js.map + +/***/ }), + +/***/ 28160: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=parser.js.map + +/***/ }), + +/***/ 8446: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.string = void 0; +const utils_1 = __webpack_require__(22049); +const bytes_1 = __webpack_require__(99356); +exports.string = { + isDynamic: true, + /** + * Check if a type is a string type. Since `string` is a simple type, this + * is just a check if the type is "string". + * + * @param type - The type to check. + * @returns Whether the type is a string type. + */ + isType: (type) => type === 'string', + /** + * Get the byte length of an encoded string type. Since `string` is a simple + * type, this will always return 32. + * + * Note that actual strings are variable in length, but the encoded static + * value (pointer) is always 32 bytes long. + * + * @returns The byte length of an encoded string. + */ + getByteLength() { + return 32; + }, + /** + * Encode the given string value to a byte array. + * + * @param args - The encoding arguments. + * @param args.buffer - The byte array to add to. + * @param args.value - The string value to encode. + * @param args.packed - Whether to use packed encoding. + * @param args.tight - Whether to use non-standard tight encoding. + * @returns The bytes with the encoded string value added to it. + */ + encode({ buffer, value, packed, tight }) { + // Strings are encoded as UTF-8 bytes, so we use the bytes parser to encode + // the string as bytes. + return bytes_1.bytes.encode({ + type: 'bytes', + buffer, + value: (0, utils_1.stringToBytes)(value), + packed, + tight, + }); + }, + /** + * Decode the given byte array to a string value. + * + * @param args - The decoding arguments. + * @returns The decoded string value. + */ + decode(args) { + // Strings are encoded as UTF-8 bytes, so we use the bytes parser to decode + // the bytes, and convert them to a string. + return (0, utils_1.bytesToString)(bytes_1.bytes.decode(args)); + }, +}; +//# sourceMappingURL=string.js.map + +/***/ }), + +/***/ 30717: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.tuple = exports.getTupleElements = void 0; +const utils_1 = __webpack_require__(22049); +const errors_1 = __webpack_require__(5961); +const packer_1 = __webpack_require__(37700); +const TUPLE_REGEX = /^\((.+)\)$/u; +const isTupleType = (type) => TUPLE_REGEX.test(type); +/** + * Get elements from a tuple type. + * + * @param type - The tuple type to get the types for. + * @returns The elements of the tuple as string array. + */ +const getTupleElements = (type) => { + (0, utils_1.assert)(type.startsWith('(') && type.endsWith(')'), new errors_1.ParserError(`Invalid tuple type. Expected tuple type, but received "${type}".`)); + const elements = []; + let current = ''; + let depth = 0; + for (let i = 1; i < type.length - 1; i++) { + const char = type[i]; + if (char === ',' && depth === 0) { + elements.push(current.trim()); + current = ''; + } + else { + current += char; + if (char === '(') { + depth += 1; + } + else if (char === ')') { + depth -= 1; + } + } + } + if (current.trim()) { + elements.push(current.trim()); + } + return elements; +}; +exports.getTupleElements = getTupleElements; +exports.tuple = { + /** + * Check if the tuple is dynamic. Tuples are dynamic if one or more elements + * of the tuple are dynamic. + * + * @param type - The type to check. + * @returns Whether the tuple is dynamic. + */ + isDynamic(type) { + const elements = (0, exports.getTupleElements)(type); + return elements.some((element) => { + const parser = (0, packer_1.getParser)(element); + return (0, packer_1.isDynamicParser)(parser, element); + }); + }, + /** + * Check if a type is a tuple type. + * + * @param type - The type to check. + * @returns Whether the type is a tuple type. + */ + isType(type) { + return isTupleType(type); + }, + /** + * Get the byte length of a tuple type. If the tuple is dynamic, this will + * always return 32. If the tuple is static, this will return the sum of the + * byte lengths of the tuple elements. + * + * @param type - The type to get the byte length for. + * @returns The byte length of the tuple type. + */ + getByteLength(type) { + if ((0, packer_1.isDynamicParser)(this, type)) { + return 32; + } + const elements = (0, exports.getTupleElements)(type); + return elements.reduce((total, element) => { + return total + (0, packer_1.getParser)(element).getByteLength(element); + }, 0); + }, + /** + * Encode a tuple value. + * + * @param args - The encoding arguments. + * @param args.type - The type of the value. + * @param args.buffer - The byte array to add to. + * @param args.value - The value to encode. + * @param args.packed - Whether to use non-standard packed encoding. + * @param args.tight - Whether to use non-standard tight encoding. + * @returns The bytes with the encoded value added to it. + */ + encode({ type, buffer, value, packed, tight }) { + const elements = (0, exports.getTupleElements)(type); + return (0, packer_1.pack)({ + types: elements, + values: value, + byteArray: buffer, + packed, + tight, + }); + }, + /** + * Decode a tuple value. + * + * @param args - The decoding arguments. + * @param args.type - The type of the value. + * @param args.value - The value to decode. + * @param args.skip - A function to skip a number of bytes. + * @returns The decoded value. + */ + decode({ type, value, skip }) { + const elements = (0, exports.getTupleElements)(type); + const length = this.getByteLength(type) - 32; + skip(length); + return (0, packer_1.unpack)(elements, value); + }, +}; +//# sourceMappingURL=tuple.js.map + +/***/ }), + +/***/ 15744: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=abi.js.map + +/***/ }), + +/***/ 11126: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(15744), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 59194: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.padEnd = exports.padStart = exports.set = void 0; +const utils_1 = __webpack_require__(22049); +const BUFFER_WIDTH = 32; +/** + * Set `buffer` in `target` at the specified position. + * + * @param target - The buffer to set to. + * @param buffer - The buffer to set in the target. + * @param position - The position at which to set the target. + * @returns The combined buffer. + */ +const set = (target, buffer, position) => { + return (0, utils_1.concatBytes)([ + target.subarray(0, position), + buffer, + target.subarray(position + buffer.length), + ]); +}; +exports.set = set; +/** + * Add padding to a buffer. If the buffer is larger than `length`, this function won't do anything. If it's smaller, the + * buffer will be padded to the specified length, with extra zeroes at the start. + * + * @param buffer - The buffer to add padding to. + * @param length - The number of bytes to pad the buffer to. + * @returns The padded buffer. + */ +const padStart = (buffer, length = BUFFER_WIDTH) => { + const padding = new Uint8Array(Math.max(length - buffer.length, 0)).fill(0x00); + return (0, utils_1.concatBytes)([padding, buffer]); +}; +exports.padStart = padStart; +/** + * Add padding to a buffer. If the buffer is larger than `length`, this function won't do anything. If it's smaller, the + * buffer will be padded to the specified length, with extra zeroes at the end. + * + * @param buffer - The buffer to add padding to. + * @param length - The number of bytes to pad the buffer to. + * @returns The padded buffer. + */ +const padEnd = (buffer, length = BUFFER_WIDTH) => { + const padding = new Uint8Array(Math.max(length - buffer.length, 0)).fill(0x00); + return (0, utils_1.concatBytes)([buffer, padding]); +}; +exports.padEnd = padEnd; +//# sourceMappingURL=buffer.js.map + +/***/ }), + +/***/ 26365: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(59194), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 98537: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEncryptionPublicKey = exports.decryptSafely = exports.decrypt = exports.encryptSafely = exports.encrypt = void 0; +const nacl = __importStar(__webpack_require__(88947)); +const naclUtil = __importStar(__webpack_require__(76386)); +const utils_1 = __webpack_require__(54907); +/** + * Encrypt a message. + * + * @param options - The encryption options. + * @param options.publicKey - The public key of the message recipient. + * @param options.data - The message data. + * @param options.version - The type of encryption to use. + * @returns The encrypted data. + */ +function encrypt({ publicKey, data, version, }) { + if ((0, utils_1.isNullish)(publicKey)) { + throw new Error('Missing publicKey parameter'); + } + else if ((0, utils_1.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_1.isNullish)(version)) { + throw new Error('Missing version parameter'); + } + switch (version) { + case 'x25519-xsalsa20-poly1305': { + if (typeof data !== 'string') { + throw new Error('Message data must be given as a string'); + } + // generate ephemeral keypair + const ephemeralKeyPair = nacl.box.keyPair(); + // assemble encryption parameters - from string to UInt8 + let pubKeyUInt8Array; + try { + pubKeyUInt8Array = naclUtil.decodeBase64(publicKey); + } + catch (err) { + throw new Error('Bad public key'); + } + const msgParamsUInt8Array = naclUtil.decodeUTF8(data); + const nonce = nacl.randomBytes(nacl.box.nonceLength); + // encrypt + const encryptedMessage = nacl.box(msgParamsUInt8Array, nonce, pubKeyUInt8Array, ephemeralKeyPair.secretKey); + // handle encrypted data + const output = { + version: 'x25519-xsalsa20-poly1305', + nonce: naclUtil.encodeBase64(nonce), + ephemPublicKey: naclUtil.encodeBase64(ephemeralKeyPair.publicKey), + ciphertext: naclUtil.encodeBase64(encryptedMessage), + }; + // return encrypted msg data + return output; + } + default: + throw new Error('Encryption type/version not supported'); + } +} +exports.encrypt = encrypt; +/** + * Encrypt a message in a way that obscures the message length. + * + * The message is padded to a multiple of 2048 before being encrypted so that the length of the + * resulting encrypted message can't be used to guess the exact length of the original message. + * + * @param options - The encryption options. + * @param options.publicKey - The public key of the message recipient. + * @param options.data - The message data. + * @param options.version - The type of encryption to use. + * @returns The encrypted data. + */ +function encryptSafely({ publicKey, data, version, }) { + if ((0, utils_1.isNullish)(publicKey)) { + throw new Error('Missing publicKey parameter'); + } + else if ((0, utils_1.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_1.isNullish)(version)) { + throw new Error('Missing version parameter'); + } + const DEFAULT_PADDING_LENGTH = 2 ** 11; + const NACL_EXTRA_BYTES = 16; + if (typeof data === 'object' && data && 'toJSON' in data) { + // remove toJSON attack vector + // TODO, check all possible children + throw new Error('Cannot encrypt with toJSON property. Please remove toJSON property'); + } + // add padding + const dataWithPadding = { + data, + padding: '', + }; + // calculate padding + const dataLength = Buffer.byteLength(JSON.stringify(dataWithPadding), 'utf-8'); + const modVal = dataLength % DEFAULT_PADDING_LENGTH; + let padLength = 0; + // Only pad if necessary + if (modVal > 0) { + padLength = DEFAULT_PADDING_LENGTH - modVal - NACL_EXTRA_BYTES; // nacl extra bytes + } + dataWithPadding.padding = '0'.repeat(padLength); + const paddedMessage = JSON.stringify(dataWithPadding); + return encrypt({ publicKey, data: paddedMessage, version }); +} +exports.encryptSafely = encryptSafely; +/** + * Decrypt a message. + * + * @param options - The decryption options. + * @param options.encryptedData - The encrypted data. + * @param options.privateKey - The private key to decrypt with. + * @returns The decrypted message. + */ +function decrypt({ encryptedData, privateKey, }) { + if ((0, utils_1.isNullish)(encryptedData)) { + throw new Error('Missing encryptedData parameter'); + } + else if ((0, utils_1.isNullish)(privateKey)) { + throw new Error('Missing privateKey parameter'); + } + switch (encryptedData.version) { + case 'x25519-xsalsa20-poly1305': { + // string to buffer to UInt8Array + const receiverPrivateKeyUint8Array = naclDecodeHex(privateKey); + const receiverEncryptionPrivateKey = nacl.box.keyPair.fromSecretKey(receiverPrivateKeyUint8Array).secretKey; + // assemble decryption parameters + const nonce = naclUtil.decodeBase64(encryptedData.nonce); + const ciphertext = naclUtil.decodeBase64(encryptedData.ciphertext); + const ephemPublicKey = naclUtil.decodeBase64(encryptedData.ephemPublicKey); + // decrypt + const decryptedMessage = nacl.box.open(ciphertext, nonce, ephemPublicKey, receiverEncryptionPrivateKey); + // return decrypted msg data + try { + if (!decryptedMessage) { + throw new Error(); + } + const output = naclUtil.encodeUTF8(decryptedMessage); + // TODO: This is probably extraneous but was kept to minimize changes during refactor + if (!output) { + throw new Error(); + } + return output; + } + catch (err) { + if (err && typeof err.message === 'string' && err.message.length) { + throw new Error(`Decryption failed: ${err.message}`); + } + throw new Error(`Decryption failed.`); + } + } + default: + throw new Error('Encryption type/version not supported.'); + } +} +exports.decrypt = decrypt; +/** + * Decrypt a message that has been encrypted using `encryptSafely`. + * + * @param options - The decryption options. + * @param options.encryptedData - The encrypted data. + * @param options.privateKey - The private key to decrypt with. + * @returns The decrypted message. + */ +function decryptSafely({ encryptedData, privateKey, }) { + if ((0, utils_1.isNullish)(encryptedData)) { + throw new Error('Missing encryptedData parameter'); + } + else if ((0, utils_1.isNullish)(privateKey)) { + throw new Error('Missing privateKey parameter'); + } + const dataWithPadding = JSON.parse(decrypt({ encryptedData, privateKey })); + return dataWithPadding.data; +} +exports.decryptSafely = decryptSafely; +/** + * Get the encryption public key for the given key. + * + * @param privateKey - The private key to generate the encryption public key with. + * @returns The encryption public key. + */ +function getEncryptionPublicKey(privateKey) { + const privateKeyUint8Array = naclDecodeHex(privateKey); + const encryptionPublicKey = nacl.box.keyPair.fromSecretKey(privateKeyUint8Array).publicKey; + return naclUtil.encodeBase64(encryptionPublicKey); +} +exports.getEncryptionPublicKey = getEncryptionPublicKey; +/** + * Convert a hex string to the UInt8Array format used by nacl. + * + * @param msgHex - The string to convert. + * @returns The converted string. + */ +function naclDecodeHex(msgHex) { + const msgBase64 = Buffer.from(msgHex, 'hex').toString('base64'); + return naclUtil.decodeBase64(msgBase64); +} +//# sourceMappingURL=encryption.js.map + +/***/ }), + +/***/ 51594: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.normalize = exports.concatSig = void 0; +__exportStar(__webpack_require__(20252), exports); +__exportStar(__webpack_require__(10169), exports); +__exportStar(__webpack_require__(98537), exports); +var utils_1 = __webpack_require__(54907); +Object.defineProperty(exports, "concatSig", ({ enumerable: true, get: function () { return utils_1.concatSig; } })); +Object.defineProperty(exports, "normalize", ({ enumerable: true, get: function () { return utils_1.normalize; } })); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 20252: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extractPublicKey = exports.recoverPersonalSignature = exports.personalSign = void 0; +const util_1 = __webpack_require__(68683); +const utils_1 = __webpack_require__(54907); +/** + * Create an Ethereum-specific signature for a message. + * + * This function is equivalent to the `eth_sign` Ethereum JSON-RPC method as specified in EIP-1417, + * as well as the MetaMask's `personal_sign` method. + * + * @param options - The personal sign options. + * @param options.privateKey - The key to sign with. + * @param options.data - The hex data to sign. + * @returns The '0x'-prefixed hex encoded signature. + */ +function personalSign({ privateKey, data, }) { + if ((0, utils_1.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_1.isNullish)(privateKey)) { + throw new Error('Missing privateKey parameter'); + } + const message = (0, utils_1.legacyToBuffer)(data); + const msgHash = (0, util_1.hashPersonalMessage)(message); + const sig = (0, util_1.ecsign)(msgHash, privateKey); + const serialized = (0, utils_1.concatSig)((0, util_1.toBuffer)(sig.v), sig.r, sig.s); + return serialized; +} +exports.personalSign = personalSign; +/** + * Recover the address of the account used to create the given Ethereum signature. The message + * must have been signed using the `personalSign` function, or an equivalent function. + * + * @param options - The signature recovery options. + * @param options.data - The hex data that was signed. + * @param options.signature - The '0x'-prefixed hex encoded message signature. + * @returns The '0x'-prefixed hex encoded address of the message signer. + */ +function recoverPersonalSignature({ data, signature, }) { + if ((0, utils_1.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_1.isNullish)(signature)) { + throw new Error('Missing signature parameter'); + } + const publicKey = getPublicKeyFor(data, signature); + const sender = (0, util_1.publicToAddress)(publicKey); + const senderHex = (0, util_1.bufferToHex)(sender); + return senderHex; +} +exports.recoverPersonalSignature = recoverPersonalSignature; +/** + * Recover the public key of the account used to create the given Ethereum signature. The message + * must have been signed using the `personalSign` function, or an equivalent function. + * + * @param options - The public key recovery options. + * @param options.data - The hex data that was signed. + * @param options.signature - The '0x'-prefixed hex encoded message signature. + * @returns The '0x'-prefixed hex encoded public key of the message signer. + */ +function extractPublicKey({ data, signature, }) { + if ((0, utils_1.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_1.isNullish)(signature)) { + throw new Error('Missing signature parameter'); + } + const publicKey = getPublicKeyFor(data, signature); + return `0x${publicKey.toString('hex')}`; +} +exports.extractPublicKey = extractPublicKey; +/** + * Get the public key for the given signature and message. + * + * @param message - The message that was signed. + * @param signature - The '0x'-prefixed hex encoded message signature. + * @returns The public key of the signer. + */ +function getPublicKeyFor(message, signature) { + const messageHash = (0, util_1.hashPersonalMessage)((0, utils_1.legacyToBuffer)(message)); + return (0, utils_1.recoverPublicKey)(messageHash, signature); +} +//# sourceMappingURL=personal-sign.js.map + +/***/ }), + +/***/ 10169: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.recoverTypedSignature = exports.signTypedData = exports.typedSignatureHash = exports.TypedDataUtils = exports.TYPED_MESSAGE_SCHEMA = exports.SignTypedDataVersion = void 0; +const util_1 = __webpack_require__(68683); +const abi_utils_1 = __webpack_require__(93256); +const parsers_1 = __webpack_require__(46207); +const utils_1 = __webpack_require__(26365); +const utils_2 = __webpack_require__(22049); +const keccak_1 = __webpack_require__(32019); +const utils_3 = __webpack_require__(54907); +/** + * Represents the version of `signTypedData` being used. + * + * V1 is based upon [an early version of + * EIP-712](https://github.com/ethereum/EIPs/pull/712/commits/21abe254fe0452d8583d5b132b1d7be87c0439ca) + * that lacked some later security improvements, and should generally be neglected in favor of + * later versions. + * + * V3 is based on EIP-712, except that arrays and recursive data structures are not supported. + * + * V4 is based on EIP-712, and includes full support of arrays and recursive data structures. + */ +var SignTypedDataVersion; +(function (SignTypedDataVersion) { + SignTypedDataVersion["V1"] = "V1"; + SignTypedDataVersion["V3"] = "V3"; + SignTypedDataVersion["V4"] = "V4"; +})(SignTypedDataVersion = exports.SignTypedDataVersion || (exports.SignTypedDataVersion = {})); +exports.TYPED_MESSAGE_SCHEMA = { + type: 'object', + properties: { + types: { + type: 'object', + additionalProperties: { + type: 'array', + items: { + type: 'object', + properties: { + name: { type: 'string' }, + type: { type: 'string' }, + }, + required: ['name', 'type'], + }, + }, + }, + primaryType: { type: 'string' }, + domain: { type: 'object' }, + message: { type: 'object' }, + }, + required: ['types', 'primaryType', 'domain', 'message'], +}; +/** + * Validate that the given value is a valid version string. + * + * @param version - The version value to validate. + * @param allowedVersions - A list of allowed versions. If omitted, all versions are assumed to be + * allowed. + */ +function validateVersion(version, allowedVersions) { + if (!Object.keys(SignTypedDataVersion).includes(version)) { + throw new Error(`Invalid version: '${version}'`); + } + else if (allowedVersions && !allowedVersions.includes(version)) { + throw new Error(`SignTypedDataVersion not allowed: '${version}'. Allowed versions are: ${allowedVersions.join(', ')}`); + } +} +/** + * Parse a string, number, or bigint value into a `Uint8Array`. + * + * @param type - The type of the value. + * @param value - The value to parse. + * @returns The parsed value. + */ +function parseNumber(type, value) { + (0, utils_2.assert)(value !== null, `Unable to encode value: Invalid number. Expected a valid number value, but received "${value}".`); + const bigIntValue = BigInt(value); + const length = (0, parsers_1.getLength)(type); + const maxValue = BigInt(2) ** BigInt(length) - BigInt(1); + // Note that this is not accurate, since the actual maximum value for unsigned + // integers is `2 ^ (length - 1) - 1`, but this is required for backwards + // compatibility with the old implementation. + (0, utils_2.assert)(bigIntValue >= -maxValue && bigIntValue <= maxValue, `Unable to encode value: Number "${value}" is out of range for type "${type}".`); + return bigIntValue; +} +/** + * Parse an address string to a `Uint8Array`. The behaviour of this is quite + * strange, in that it does not parse the address as hexadecimal string, nor as + * UTF-8. It does some weird stuff with the string and char codes, and then + * returns the result as a `Uint8Array`. + * + * This is based on the old `ethereumjs-abi` implementation, which essentially + * calls `new BN(address, 10)` on the address string, the equivalent of calling + * `parseInt(address, 10)` in JavaScript. This is not a valid way to parse an + * address and would result in `NaN` in plain JavaScript, but it is the + * behaviour of the old implementation, and so we must preserve it for backwards + * compatibility. + * + * @param address - The address to parse. + * @returns The parsed address. + */ +function reallyStrangeAddressToBytes(address) { + let addressValue = BigInt(0); + for (let i = 0; i < address.length; i++) { + const character = BigInt(address.charCodeAt(i) - 48); + addressValue *= BigInt(10); + // 'a' + if (character >= 49) { + addressValue += character - BigInt(49) + BigInt(0xa); + // 'A' + } + else if (character >= 17) { + addressValue += character - BigInt(17) + BigInt(0xa); + // '0' - '9' + } + else { + addressValue += character; + } + } + return (0, utils_1.padStart)((0, utils_2.bigIntToBytes)(addressValue), 20); +} +/** + * Encode a single field. + * + * @param types - All type definitions. + * @param name - The name of the field to encode. + * @param type - The type of the field being encoded. + * @param value - The value to encode. + * @param version - The EIP-712 version the encoding should comply with. + * @returns Encoded representation of the field. + */ +function encodeField(types, name, type, +// TODO: constrain type on `value` +value, version) { + validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); + if (types[type] !== undefined) { + return [ + 'bytes32', + // TODO: return Buffer, remove string from return type + version === SignTypedDataVersion.V4 && value == null // eslint-disable-line no-eq-null + ? '0x0000000000000000000000000000000000000000000000000000000000000000' + : (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(encodeData(type, value, types, version))), + ]; + } + // `function` is supported in `@metamask/abi-utils`, but not allowed by + // EIP-712, so we throw an error here. + if (type === 'function') { + throw new Error('Unsupported or invalid type: "function"'); + } + if (value === undefined) { + throw new Error(`missing value for field ${name} of type ${type}`); + } + if (type === 'address') { + if (typeof value === 'number') { + return ['address', (0, utils_1.padStart)((0, utils_2.numberToBytes)(value), 20)]; + } + else if ((0, utils_2.isStrictHexString)(value)) { + return ['address', (0, utils_2.add0x)(value)]; + } + else if (typeof value === 'string') { + return ['address', reallyStrangeAddressToBytes(value).subarray(0, 20)]; + } + } + if (type === 'bool') { + return ['bool', Boolean(value)]; + } + if (type === 'bytes') { + if (typeof value === 'number') { + value = (0, utils_2.numberToBytes)(value); + } + else if ((0, utils_2.isStrictHexString)(value) || value === '0x') { + value = (0, utils_2.hexToBytes)(value); + } + else if (typeof value === 'string') { + value = (0, utils_2.stringToBytes)(value); + } + return ['bytes32', (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(value))]; + } + if (type.startsWith('bytes') && type !== 'bytes' && !type.includes('[')) { + if (typeof value === 'number') { + if (value < 0) { + return ['bytes32', new Uint8Array(32)]; + } + return ['bytes32', (0, utils_2.bigIntToBytes)(BigInt(value))]; + } + else if ((0, utils_2.isStrictHexString)(value)) { + return ['bytes32', (0, utils_2.hexToBytes)(value)]; + } + return ['bytes32', value]; + } + if (type.startsWith('int') && !type.includes('[')) { + const bigIntValue = parseNumber(type, value); + if (bigIntValue >= BigInt(0)) { + return ['uint256', bigIntValue]; + } + return ['int256', bigIntValue]; + } + if (type === 'string') { + if (typeof value === 'number') { + value = (0, utils_2.numberToBytes)(value); + } + else { + value = (0, utils_2.stringToBytes)(value !== null && value !== void 0 ? value : ''); + } + return ['bytes32', (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(value))]; + } + if (type.endsWith(']')) { + if (version === SignTypedDataVersion.V3) { + throw new Error('Arrays are unimplemented in encodeData; use V4 extension'); + } + const parsedType = type.slice(0, type.lastIndexOf('[')); + const typeValuePairs = value.map((item) => encodeField(types, name, parsedType, item, version)); + return [ + 'bytes32', + (0, util_1.arrToBufArr)((0, keccak_1.keccak256)((0, abi_utils_1.encode)(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))), + ]; + } + return [type, value]; +} +/** + * Encodes an object by encoding and concatenating each of its members. + * + * @param primaryType - The root type. + * @param data - The object to encode. + * @param types - Type definitions for all types included in the message. + * @param version - The EIP-712 version the encoding should comply with. + * @returns An encoded representation of an object. + */ +function encodeData(primaryType, data, types, version) { + validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); + const encodedTypes = ['bytes32']; + const encodedValues = [ + hashType(primaryType, types), + ]; + for (const field of types[primaryType]) { + if (version === SignTypedDataVersion.V3 && data[field.name] === undefined) { + continue; + } + const [type, value] = encodeField(types, field.name, field.type, data[field.name], version); + encodedTypes.push(type); + encodedValues.push(value); + } + return (0, util_1.arrToBufArr)((0, abi_utils_1.encode)(encodedTypes, encodedValues)); +} +/** + * Encodes the type of an object by encoding a comma delimited list of its members. + * + * @param primaryType - The root type to encode. + * @param types - Type definitions for all types included in the message. + * @returns An encoded representation of the primary type. + */ +function encodeType(primaryType, types) { + let result = ''; + const unsortedDeps = findTypeDependencies(primaryType, types); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + const children = types[type]; + if (!children) { + throw new Error(`No type definition specified: ${type}`); + } + result += `${type}(${types[type] + .map(({ name, type: t }) => `${t} ${name}`) + .join(',')})`; + } + return result; +} +/** + * Finds all types within a type definition object. + * + * @param primaryType - The root type. + * @param types - Type definitions for all types included in the message. + * @param results - The current set of accumulated types. + * @returns The set of all types found in the type definition. + */ +function findTypeDependencies(primaryType, types, results = new Set()) { + if (typeof primaryType !== 'string') { + throw new Error(`Invalid findTypeDependencies input ${JSON.stringify(primaryType)}`); + } + const match = primaryType.match(/^\w*/u); + [primaryType] = match; + if (results.has(primaryType) || types[primaryType] === undefined) { + return results; + } + results.add(primaryType); + for (const field of types[primaryType]) { + findTypeDependencies(field.type, types, results); + } + return results; +} +/** + * Hashes an object. + * + * @param primaryType - The root type. + * @param data - The object to hash. + * @param types - Type definitions for all types included in the message. + * @param version - The EIP-712 version the encoding should comply with. + * @returns The hash of the object. + */ +function hashStruct(primaryType, data, types, version) { + validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); + const encoded = encodeData(primaryType, data, types, version); + const hashed = (0, keccak_1.keccak256)(encoded); + const buf = (0, util_1.arrToBufArr)(hashed); + return buf; +} +/** + * Hashes the type of an object. + * + * @param primaryType - The root type to hash. + * @param types - Type definitions for all types included in the message. + * @returns The hash of the object type. + */ +function hashType(primaryType, types) { + const encodedHashType = (0, utils_2.stringToBytes)(encodeType(primaryType, types)); + return (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(encodedHashType)); +} +/** + * Removes properties from a message object that are not defined per EIP-712. + * + * @param data - The typed message object. + * @returns The typed message object with only allowed fields. + */ +function sanitizeData(data) { + const sanitizedData = {}; + for (const key in exports.TYPED_MESSAGE_SCHEMA.properties) { + if (data[key]) { + sanitizedData[key] = data[key]; + } + } + if ('types' in sanitizedData) { + // TODO: Fix types + sanitizedData.types = Object.assign({ EIP712Domain: [] }, sanitizedData.types); + } + return sanitizedData; +} +/** + * Create a EIP-712 Domain Hash. + * This hash is used at the top of the EIP-712 encoding. + * + * @param typedData - The typed message to hash. + * @param version - The EIP-712 version the encoding should comply with. + * @returns The hash of the domain object. + */ +function eip712DomainHash(typedData, version) { + validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); + const sanitizedData = sanitizeData(typedData); + const { domain } = sanitizedData; + const domainType = { EIP712Domain: sanitizedData.types.EIP712Domain }; + return hashStruct('EIP712Domain', domain, domainType, version); +} +/** + * Hash a typed message according to EIP-712. The returned message starts with the EIP-712 prefix, + * which is "1901", followed by the hash of the domain separator, then the data (if any). + * The result is hashed again and returned. + * + * This function does not sign the message. The resulting hash must still be signed to create an + * EIP-712 signature. + * + * @param typedData - The typed message to hash. + * @param version - The EIP-712 version the encoding should comply with. + * @returns The hash of the typed message. + */ +function eip712Hash(typedData, version) { + validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); + const sanitizedData = sanitizeData(typedData); + const parts = [(0, utils_2.hexToBytes)('1901')]; + parts.push(eip712DomainHash(typedData, version)); + if (sanitizedData.primaryType !== 'EIP712Domain') { + parts.push(hashStruct( + // TODO: Validate that this is a string, so this type cast can be removed. + sanitizedData.primaryType, sanitizedData.message, sanitizedData.types, version)); + } + return (0, util_1.arrToBufArr)((0, keccak_1.keccak256)((0, utils_2.concatBytes)(parts))); +} +/** + * A collection of utility functions used for signing typed data. + */ +exports.TypedDataUtils = { + encodeData, + encodeType, + findTypeDependencies, + hashStruct, + hashType, + sanitizeData, + eip712Hash, + eip712DomainHash, +}; +/** + * Generate the "V1" hash for the provided typed message. + * + * The hash will be generated in accordance with an earlier version of the EIP-712 + * specification. This hash is used in `signTypedData_v1`. + * + * @param typedData - The typed message. + * @returns The '0x'-prefixed hex encoded hash representing the type of the provided message. + */ +function typedSignatureHash(typedData) { + const hashBuffer = _typedSignatureHash(typedData); + return (0, utils_2.bytesToHex)(hashBuffer); +} +exports.typedSignatureHash = typedSignatureHash; +/** + * Normalize a value, so that `@metamask/abi-utils` can handle it. This + * matches the behaviour of the `ethereumjs-abi` library. + * + * @param type - The type of the value to normalize. + * @param value - The value to normalize. + * @returns The normalized value. + */ +function normalizeValue(type, value) { + if ((0, parsers_1.isArrayType)(type) && Array.isArray(value)) { + const [innerType] = (0, parsers_1.getArrayType)(type); + return value.map((item) => normalizeValue(innerType, item)); + } + if (type === 'address') { + if (typeof value === 'number') { + return (0, utils_1.padStart)((0, utils_2.numberToBytes)(value), 20); + } + if ((0, utils_2.isStrictHexString)(value)) { + return (0, utils_1.padStart)((0, utils_2.hexToBytes)(value).subarray(0, 20), 20); + } + if (value instanceof Uint8Array) { + return (0, utils_1.padStart)(value.subarray(0, 20), 20); + } + } + if (type === 'bool') { + return Boolean(value); + } + if (type.startsWith('bytes') && type !== 'bytes') { + const length = (0, parsers_1.getByteLength)(type); + if (typeof value === 'number') { + if (value < 0) { + // `solidityPack(['bytesN'], [-1])` returns `0x00..00`. + return new Uint8Array(); + } + return (0, utils_2.numberToBytes)(value).subarray(0, length); + } + if ((0, utils_2.isStrictHexString)(value)) { + return (0, utils_2.hexToBytes)(value).subarray(0, length); + } + if (value instanceof Uint8Array) { + return value.subarray(0, length); + } + } + if (type.startsWith('uint')) { + if (typeof value === 'number') { + return Math.abs(value); + } + } + if (type.startsWith('int')) { + if (typeof value === 'number') { + const length = (0, parsers_1.getLength)(type); + return BigInt.asIntN(length, BigInt(value)); + } + } + return value; +} +/** + * For some reason `ethereumjs-abi` treats `address` and `address[]` differently + * so we need to normalize `address[]` differently. + * + * @param values - The values to normalize. + * @returns The normalized values. + */ +function normalizeAddresses(values) { + return values.map((value) => { + if (typeof value === 'number') { + return (0, utils_1.padStart)((0, utils_2.numberToBytes)(value), 32); + } + if ((0, utils_2.isStrictHexString)(value)) { + return (0, utils_1.padStart)((0, utils_2.hexToBytes)(value).subarray(0, 32), 32); + } + if (value instanceof Uint8Array) { + return (0, utils_1.padStart)(value.subarray(0, 32), 32); + } + return value; + }); +} +/** + * For some reason `ethereumjs-abi` treats `intN` and `intN[]` differently + * so we need to normalize `intN[]` differently. + * + * @param type - The type of the value to normalize. + * @param values - The values to normalize. + * @returns The normalized values. + */ +function normalizeIntegers(type, values) { + return values.map((value) => { + if (typeof value === 'string' || + typeof value === 'number' || + typeof value === 'bigint') { + const bigIntValue = parseNumber(type, value); + if (bigIntValue >= BigInt(0)) { + return (0, utils_1.padStart)((0, utils_2.bigIntToBytes)(bigIntValue), 32); + } + const length = (0, parsers_1.getLength)(type); + const asIntN = BigInt.asIntN(length, bigIntValue); + return (0, utils_2.signedBigIntToBytes)(asIntN, 32); + } + return value; + }); +} +/** + * Generate the "V1" hash for the provided typed message. + * + * The hash will be generated in accordance with an earlier version of the EIP-712 + * specification. This hash is used in `signTypedData_v1`. + * + * @param typedData - The typed message. + * @returns The hash representing the type of the provided message. + */ +function _typedSignatureHash(typedData) { + const error = new Error('Expect argument to be non-empty array'); + if (typeof typedData !== 'object' || + !('length' in typedData) || + !typedData.length) { + throw error; + } + const normalizedData = typedData.map(({ name, type, value }) => { + // Handle an edge case with `address[]` types. + if (type === 'address[]') { + return { + name, + type: 'bytes32[]', + value: normalizeAddresses(value), + }; + } + // Handle an edge case with `intN[]` types. + if (type.startsWith('int') && (0, parsers_1.isArrayType)(type)) { + const [innerType, length] = (0, parsers_1.getArrayType)(type); + return { + name, + type: `bytes32[${length !== null && length !== void 0 ? length : ''}]`, + value: normalizeIntegers(innerType, value), + }; + } + return { + name, + type, + value: normalizeValue(type, value), + }; + }); + const data = normalizedData.map((e) => { + if (e.type !== 'bytes') { + return e.value; + } + return (0, utils_3.legacyToBuffer)(e.value); + }); + const types = normalizedData.map((e) => { + if (e.type === 'function') { + throw new Error('Unsupported or invalid type: "function"'); + } + return e.type; + }); + const schema = typedData.map((e) => { + if (!e.name) { + throw error; + } + return `${e.type} ${e.name}`; + }); + return (0, util_1.arrToBufArr)((0, keccak_1.keccak256)((0, abi_utils_1.encodePacked)(['bytes32', 'bytes32'], [ + (0, keccak_1.keccak256)((0, abi_utils_1.encodePacked)(['string[]'], [schema], true)), + (0, keccak_1.keccak256)((0, abi_utils_1.encodePacked)(types, data, true)), + ]))); +} +/** + * Sign typed data according to EIP-712. The signing differs based upon the `version`. + * + * V1 is based upon [an early version of + * EIP-712](https://github.com/ethereum/EIPs/pull/712/commits/21abe254fe0452d8583d5b132b1d7be87c0439ca) + * that lacked some later security improvements, and should generally be neglected in favor of + * later versions. + * + * V3 is based on [EIP-712](https://eips.ethereum.org/EIPS/eip-712), except that arrays and + * recursive data structures are not supported. + * + * V4 is based on [EIP-712](https://eips.ethereum.org/EIPS/eip-712), and includes full support of + * arrays and recursive data structures. + * + * @param options - The signing options. + * @param options.privateKey - The private key to sign with. + * @param options.data - The typed data to sign. + * @param options.version - The signing version to use. + * @returns The '0x'-prefixed hex encoded signature. + */ +function signTypedData({ privateKey, data, version, }) { + validateVersion(version); + if ((0, utils_3.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_3.isNullish)(privateKey)) { + throw new Error('Missing private key parameter'); + } + const messageHash = version === SignTypedDataVersion.V1 + ? _typedSignatureHash(data) + : exports.TypedDataUtils.eip712Hash(data, version); + const sig = (0, util_1.ecsign)(messageHash, privateKey); + return (0, utils_3.concatSig)((0, util_1.arrToBufArr)((0, utils_2.bigIntToBytes)(sig.v)), sig.r, sig.s); +} +exports.signTypedData = signTypedData; +/** + * Recover the address of the account that created the given EIP-712 + * signature. The version provided must match the version used to + * create the signature. + * + * @param options - The signature recovery options. + * @param options.data - The typed data that was signed. + * @param options.signature - The '0x-prefixed hex encoded message signature. + * @param options.version - The signing version to use. + * @returns The '0x'-prefixed hex address of the signer. + */ +function recoverTypedSignature({ data, signature, version, }) { + validateVersion(version); + if ((0, utils_3.isNullish)(data)) { + throw new Error('Missing data parameter'); + } + else if ((0, utils_3.isNullish)(signature)) { + throw new Error('Missing signature parameter'); + } + const messageHash = version === SignTypedDataVersion.V1 + ? _typedSignatureHash(data) + : exports.TypedDataUtils.eip712Hash(data, version); + const publicKey = (0, utils_3.recoverPublicKey)(messageHash, signature); + const sender = (0, util_1.publicToAddress)(publicKey); + return (0, utils_2.bytesToHex)(sender); +} +exports.recoverTypedSignature = recoverTypedSignature; +//# sourceMappingURL=sign-typed-data.js.map + +/***/ }), + +/***/ 54907: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.normalize = exports.recoverPublicKey = exports.concatSig = exports.legacyToBuffer = exports.isNullish = exports.padWithZeroes = void 0; +const util_1 = __webpack_require__(68683); +const utils_1 = __webpack_require__(22049); +/** + * Pads the front of the given hex string with zeroes until it reaches the + * target length. If the input string is already longer than or equal to the + * target length, it is returned unmodified. + * + * If the input string is "0x"-prefixed or not a hex string, an error will be + * thrown. + * + * @param hexString - The hexadecimal string to pad with zeroes. + * @param targetLength - The target length of the hexadecimal string. + * @returns The input string front-padded with zeroes, or the original string + * if it was already greater than or equal to to the target length. + */ +function padWithZeroes(hexString, targetLength) { + if (hexString !== '' && !/^[a-f0-9]+$/iu.test(hexString)) { + throw new Error(`Expected an unprefixed hex string. Received: ${hexString}`); + } + if (targetLength < 0) { + throw new Error(`Expected a non-negative integer target length. Received: ${targetLength}`); + } + return String.prototype.padStart.call(hexString, targetLength, '0'); +} +exports.padWithZeroes = padWithZeroes; +/** + * Returns `true` if the given value is nullish. + * + * @param value - The value being checked. + * @returns Whether the value is nullish. + */ +function isNullish(value) { + return value === null || value === undefined; +} +exports.isNullish = isNullish; +/** + * Convert a value to a Buffer. This function should be equivalent to the `toBuffer` function in + * `ethereumjs-util@5.2.1`. + * + * @param value - The value to convert to a Buffer. + * @returns The given value as a Buffer. + */ +function legacyToBuffer(value) { + return typeof value === 'string' && !(0, util_1.isHexString)(value) + ? Buffer.from(value) + : (0, util_1.toBuffer)(value); +} +exports.legacyToBuffer = legacyToBuffer; +/** + * Concatenate an extended ECDSA signature into a single '0x'-prefixed hex string. + * + * @param v - The 'v' portion of the signature. + * @param r - The 'r' portion of the signature. + * @param s - The 's' portion of the signature. + * @returns The concatenated ECDSA signature as a '0x'-prefixed string. + */ +function concatSig(v, r, s) { + const rSig = (0, util_1.fromSigned)(r); + const sSig = (0, util_1.fromSigned)(s); + const vSig = (0, util_1.bufferToInt)(v); + const rStr = padWithZeroes((0, util_1.toUnsigned)(rSig).toString('hex'), 64); + const sStr = padWithZeroes((0, util_1.toUnsigned)(sSig).toString('hex'), 64); + const vStr = (0, utils_1.remove0x)((0, utils_1.numberToHex)(vSig)); + return (0, utils_1.add0x)(rStr.concat(sStr, vStr)); +} +exports.concatSig = concatSig; +/** + * Recover the public key from the given signature and message hash. + * + * @param messageHash - The hash of the signed message. + * @param signature - The signature. + * @returns The public key of the signer. + */ +function recoverPublicKey(messageHash, signature) { + const sigParams = (0, util_1.fromRpcSig)(signature); + return (0, util_1.ecrecover)(messageHash, sigParams.v, sigParams.r, sigParams.s); +} +exports.recoverPublicKey = recoverPublicKey; +/** + * Normalize the input to a lower-cased '0x'-prefixed hex string. + * + * @param input - The value to normalize. + * @returns The normalized value. + */ +function normalize(input) { + if (isNullish(input)) { + return undefined; + } + if (typeof input === 'number') { + if (input < 0) { + return '0x'; + } + const buffer = (0, utils_1.numberToBytes)(input); + input = (0, utils_1.bytesToHex)(buffer); + } + if (typeof input !== 'string') { + let msg = 'eth-sig-util.normalize() requires hex string or integer input.'; + msg += ` received ${typeof input}: ${input}`; + throw new Error(msg); + } + return (0, utils_1.add0x)(input.toLowerCase()); +} +exports.normalize = normalize; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 61275: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/logging.ts +var _debug = __webpack_require__(17833); var _debug2 = _interopRequireDefault(_debug); +var globalLogger = _debug2.default.call(void 0, "metamask"); +function createProjectLogger(projectName) { + return globalLogger.extend(projectName); +} +function createModuleLogger(projectLogger, moduleName) { + return projectLogger.extend(moduleName); +} + + + + +exports.createProjectLogger = createProjectLogger; exports.createModuleLogger = createModuleLogger; +//# sourceMappingURL=chunk-2LBGT4GH.js.map + +/***/ }), + +/***/ 85244: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true}));var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + + + + + +exports.__privateGet = __privateGet; exports.__privateAdd = __privateAdd; exports.__privateSet = __privateSet; +//# sourceMappingURL=chunk-3W5G4CYI.js.map + +/***/ }), + +/***/ 73631: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + +// src/versions.ts + + + + + + +var _semver = __webpack_require__(99589); +var _superstruct = __webpack_require__(2150); +var VersionStruct = _superstruct.refine.call(void 0, + _superstruct.string.call(void 0, ), + "Version", + (value) => { + if (_semver.valid.call(void 0, value) === null) { + return `Expected SemVer version, got "${value}"`; + } + return true; + } +); +var VersionRangeStruct = _superstruct.refine.call(void 0, + _superstruct.string.call(void 0, ), + "Version range", + (value) => { + if (_semver.validRange.call(void 0, value) === null) { + return `Expected SemVer range, got "${value}"`; + } + return true; + } +); +function isValidSemVerVersion(version) { + return _superstruct.is.call(void 0, version, VersionStruct); +} +function isValidSemVerRange(versionRange) { + return _superstruct.is.call(void 0, versionRange, VersionRangeStruct); +} +function assertIsSemVerVersion(version) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, version, VersionStruct); +} +function assertIsSemVerRange(range) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, range, VersionRangeStruct); +} +function gtVersion(version1, version2) { + return _semver.gt.call(void 0, version1, version2); +} +function gtRange(version, range) { + return _semver.gtr.call(void 0, version, range); +} +function satisfiesVersionRange(version, versionRange) { + return _semver.satisfies.call(void 0, version, versionRange, { + includePrerelease: true + }); +} + + + + + + + + + + + +exports.VersionStruct = VersionStruct; exports.VersionRangeStruct = VersionRangeStruct; exports.isValidSemVerVersion = isValidSemVerVersion; exports.isValidSemVerRange = isValidSemVerRange; exports.assertIsSemVerVersion = assertIsSemVerVersion; exports.assertIsSemVerRange = assertIsSemVerRange; exports.gtVersion = gtVersion; exports.gtRange = gtRange; exports.satisfiesVersionRange = satisfiesVersionRange; +//# sourceMappingURL=chunk-4D6XQBHA.js.map + +/***/ }), + +/***/ 69116: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true}));// src/time.ts +var Duration = /* @__PURE__ */ ((Duration2) => { + Duration2[Duration2["Millisecond"] = 1] = "Millisecond"; + Duration2[Duration2["Second"] = 1e3] = "Second"; + Duration2[Duration2["Minute"] = 6e4] = "Minute"; + Duration2[Duration2["Hour"] = 36e5] = "Hour"; + Duration2[Duration2["Day"] = 864e5] = "Day"; + Duration2[Duration2["Week"] = 6048e5] = "Week"; + Duration2[Duration2["Year"] = 31536e6] = "Year"; + return Duration2; +})(Duration || {}); +var isNonNegativeInteger = (number) => Number.isInteger(number) && number >= 0; +var assertIsNonNegativeInteger = (number, name) => { + if (!isNonNegativeInteger(number)) { + throw new Error( + `"${name}" must be a non-negative integer. Received: "${number}".` + ); + } +}; +function inMilliseconds(count, duration) { + assertIsNonNegativeInteger(count, "count"); + return count * duration; +} +function timeSince(timestamp) { + assertIsNonNegativeInteger(timestamp, "timestamp"); + return Date.now() - timestamp; +} + + + + + +exports.Duration = Duration; exports.inMilliseconds = inMilliseconds; exports.timeSince = timeSince; +//# sourceMappingURL=chunk-4RMX5YWE.js.map + +/***/ }), + +/***/ 87982: +/***/ (() => { + +"use strict"; +//# sourceMappingURL=chunk-5AVWINSB.js.map + +/***/ }), + +/***/ 21848: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + +// src/base64.ts +var _superstruct = __webpack_require__(2150); +var base64 = (struct, options = {}) => { + const paddingRequired = _nullishCoalesce(options.paddingRequired, () => ( false)); + const characterSet = _nullishCoalesce(options.characterSet, () => ( "base64")); + let letters; + if (characterSet === "base64") { + letters = String.raw`[A-Za-z0-9+\/]`; + } else { + _chunk6ZDHSOUVjs.assert.call(void 0, characterSet === "base64url"); + letters = String.raw`[-_A-Za-z0-9]`; + } + let re; + if (paddingRequired) { + re = new RegExp( + `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, + "u" + ); + } else { + re = new RegExp( + `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, + "u" + ); + } + return _superstruct.pattern.call(void 0, struct, re); +}; + + + +exports.base64 = base64; +//# sourceMappingURL=chunk-6NZW4WK4.js.map + +/***/ }), + +/***/ 40932: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } + +var _chunkIZC266HSjs = __webpack_require__(1486); + +// src/assert.ts +var _superstruct = __webpack_require__(2150); +function isConstructable(fn) { + return Boolean(typeof _optionalChain([fn, 'optionalAccess', _ => _.prototype, 'optionalAccess', _2 => _2.constructor, 'optionalAccess', _3 => _3.name]) === "string"); +} +function getErrorMessageWithoutTrailingPeriod(error) { + return _chunkIZC266HSjs.getErrorMessage.call(void 0, error).replace(/\.$/u, ""); +} +function getError(ErrorWrapper, message) { + if (isConstructable(ErrorWrapper)) { + return new ErrorWrapper({ + message + }); + } + return ErrorWrapper({ + message + }); +} +var AssertionError = class extends Error { + constructor(options) { + super(options.message); + this.code = "ERR_ASSERTION"; + } +}; +function assert(value, message = "Assertion failed.", ErrorWrapper = AssertionError) { + if (!value) { + if (message instanceof Error) { + throw message; + } + throw getError(ErrorWrapper, message); + } +} +function assertStruct(value, struct, errorPrefix = "Assertion failed", ErrorWrapper = AssertionError) { + try { + _superstruct.assert.call(void 0, value, struct); + } catch (error) { + throw getError( + ErrorWrapper, + `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.` + ); + } +} +function assertExhaustive(_object) { + throw new Error( + "Invalid branch reached. Should be detected during compilation." + ); +} + + + + + + +exports.AssertionError = AssertionError; exports.assert = assert; exports.assertStruct = assertStruct; exports.assertExhaustive = assertExhaustive; +//# sourceMappingURL=chunk-6ZDHSOUV.js.map + +/***/ }), + +/***/ 39705: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true}));// src/promise.ts +function createDeferredPromise({ + suppressUnhandledRejection = false +} = {}) { + let resolve; + let reject; + const promise = new Promise( + (innerResolve, innerReject) => { + resolve = innerResolve; + reject = innerReject; + } + ); + if (suppressUnhandledRejection) { + promise.catch((_error) => { + }); + } + return { promise, resolve, reject }; +} + + + +exports.createDeferredPromise = createDeferredPromise; +//# sourceMappingURL=chunk-C6HGFEYL.js.map + +/***/ }), + +/***/ 1203: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + + + +var _chunkQEPVHEP7js = __webpack_require__(75363); + + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + +// src/coercers.ts + + + + + + + + + +var _superstruct = __webpack_require__(2150); +var NumberLikeStruct = _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.bigint.call(void 0, ), _superstruct.string.call(void 0, ), _chunkQEPVHEP7js.StrictHexStruct]); +var NumberCoercer = _superstruct.coerce.call(void 0, _superstruct.number.call(void 0, ), NumberLikeStruct, Number); +var BigIntCoercer = _superstruct.coerce.call(void 0, _superstruct.bigint.call(void 0, ), NumberLikeStruct, BigInt); +var BytesLikeStruct = _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array)]); +var BytesCoercer = _superstruct.coerce.call(void 0, + _superstruct.instance.call(void 0, Uint8Array), + _superstruct.union.call(void 0, [_chunkQEPVHEP7js.StrictHexStruct]), + _chunkQEPVHEP7js.hexToBytes +); +var HexCoercer = _superstruct.coerce.call(void 0, _chunkQEPVHEP7js.StrictHexStruct, _superstruct.instance.call(void 0, Uint8Array), _chunkQEPVHEP7js.bytesToHex); +function createNumber(value) { + try { + const result = _superstruct.create.call(void 0, value, NumberCoercer); + _chunk6ZDHSOUVjs.assert.call(void 0, + Number.isFinite(result), + `Expected a number-like value, got "${value}".` + ); + return result; + } catch (error) { + if (error instanceof _superstruct.StructError) { + throw new Error(`Expected a number-like value, got "${value}".`); + } + throw error; + } +} +function createBigInt(value) { + try { + return _superstruct.create.call(void 0, value, BigIntCoercer); + } catch (error) { + if (error instanceof _superstruct.StructError) { + throw new Error( + `Expected a number-like value, got "${String(error.value)}".` + ); + } + throw error; + } +} +function createBytes(value) { + if (typeof value === "string" && value.toLowerCase() === "0x") { + return new Uint8Array(); + } + try { + return _superstruct.create.call(void 0, value, BytesCoercer); + } catch (error) { + if (error instanceof _superstruct.StructError) { + throw new Error( + `Expected a bytes-like value, got "${String(error.value)}".` + ); + } + throw error; + } +} +function createHex(value) { + if (value instanceof Uint8Array && value.length === 0 || typeof value === "string" && value.toLowerCase() === "0x") { + return "0x"; + } + try { + return _superstruct.create.call(void 0, value, HexCoercer); + } catch (error) { + if (error instanceof _superstruct.StructError) { + throw new Error( + `Expected a bytes-like value, got "${String(error.value)}".` + ); + } + throw error; + } +} + + + + + + +exports.createNumber = createNumber; exports.createBigInt = createBigInt; exports.createBytes = createBytes; exports.createHex = createHex; +//# sourceMappingURL=chunk-DHVKFDHQ.js.map + +/***/ }), + +/***/ 1508: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + +var _chunk6NZW4WK4js = __webpack_require__(21848); + +// src/checksum.ts +var _superstruct = __webpack_require__(2150); +var ChecksumStruct = _superstruct.size.call(void 0, + _chunk6NZW4WK4js.base64.call(void 0, _superstruct.string.call(void 0, ), { paddingRequired: true }), + 44, + 44 +); + + + +exports.ChecksumStruct = ChecksumStruct; +//# sourceMappingURL=chunk-E4C7EW4R.js.map + +/***/ }), + +/***/ 51423: +/***/ (() => { + +"use strict"; +//# sourceMappingURL=chunk-EQMZL4XU.js.map + +/***/ }), + +/***/ 1486: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + + +var _chunkQVEKZRZ2js = __webpack_require__(96526); + +// src/errors.ts +var _ponycause = __webpack_require__(71843); +function isError(error) { + return error instanceof Error || _chunkQVEKZRZ2js.isObject.call(void 0, error) && error.constructor.name === "Error"; +} +function isErrorWithCode(error) { + return typeof error === "object" && error !== null && "code" in error; +} +function isErrorWithMessage(error) { + return typeof error === "object" && error !== null && "message" in error; +} +function isErrorWithStack(error) { + return typeof error === "object" && error !== null && "stack" in error; +} +function getErrorMessage(error) { + if (isErrorWithMessage(error) && typeof error.message === "string") { + return error.message; + } + if (_chunkQVEKZRZ2js.isNullOrUndefined.call(void 0, error)) { + return ""; + } + return String(error); +} +function wrapError(originalError, message) { + if (isError(originalError)) { + let error; + if (Error.length === 2) { + error = new Error(message, { cause: originalError }); + } else { + error = new (0, _ponycause.ErrorWithCause)(message, { cause: originalError }); + } + if (isErrorWithCode(originalError)) { + error.code = originalError.code; + } + return error; + } + if (message.length > 0) { + return new Error(`${String(originalError)}: ${message}`); + } + return new Error(String(originalError)); +} + + + + + + + +exports.isErrorWithCode = isErrorWithCode; exports.isErrorWithMessage = isErrorWithMessage; exports.isErrorWithStack = isErrorWithStack; exports.getErrorMessage = getErrorMessage; exports.wrapError = wrapError; +//# sourceMappingURL=chunk-IZC266HS.js.map + +/***/ }), + +/***/ 58383: +/***/ (() => { + +"use strict"; +//# sourceMappingURL=chunk-LC2CRSWD.js.map + +/***/ }), + +/***/ 87427: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + + +var _chunkQVEKZRZ2js = __webpack_require__(96526); + +// src/json.ts + + + + + + + + + + + + + + + + + + + + +var _superstruct = __webpack_require__(2150); +var object = (schema) => ( + // The type is slightly different from a regular object struct, because we + // want to make properties with `undefined` in their type optional, but not + // `undefined` itself. This means that we need a type cast. + _superstruct.object.call(void 0, schema) +); +function hasOptional({ path, branch }) { + const field = path[path.length - 1]; + return _chunkQVEKZRZ2js.hasProperty.call(void 0, branch[branch.length - 2], field); +} +function exactOptional(struct) { + return new (0, _superstruct.Struct)({ + ...struct, + type: `optional ${struct.type}`, + validator: (value, context) => !hasOptional(context) || struct.validator(value, context), + refiner: (value, context) => !hasOptional(context) || struct.refiner(value, context) + }); +} +var finiteNumber = () => _superstruct.define.call(void 0, "finite number", (value) => { + return _superstruct.is.call(void 0, value, _superstruct.number.call(void 0, )) && Number.isFinite(value); +}); +var UnsafeJsonStruct = _superstruct.union.call(void 0, [ + _superstruct.literal.call(void 0, null), + _superstruct.boolean.call(void 0, ), + finiteNumber(), + _superstruct.string.call(void 0, ), + _superstruct.array.call(void 0, _superstruct.lazy.call(void 0, () => UnsafeJsonStruct)), + _superstruct.record.call(void 0, + _superstruct.string.call(void 0, ), + _superstruct.lazy.call(void 0, () => UnsafeJsonStruct) + ) +]); +var JsonStruct = _superstruct.coerce.call(void 0, UnsafeJsonStruct, _superstruct.any.call(void 0, ), (value) => { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, UnsafeJsonStruct); + return JSON.parse( + JSON.stringify(value, (propKey, propValue) => { + if (propKey === "__proto__" || propKey === "constructor") { + return void 0; + } + return propValue; + }) + ); +}); +function isValidJson(value) { + try { + getSafeJson(value); + return true; + } catch (e) { + return false; + } +} +function getSafeJson(value) { + return _superstruct.create.call(void 0, value, JsonStruct); +} +function getJsonSize(value) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, value, JsonStruct, "Invalid JSON value"); + const json = JSON.stringify(value); + return new TextEncoder().encode(json).byteLength; +} +var jsonrpc2 = "2.0"; +var JsonRpcVersionStruct = _superstruct.literal.call(void 0, jsonrpc2); +var JsonRpcIdStruct = _superstruct.nullable.call(void 0, _superstruct.union.call(void 0, [_superstruct.number.call(void 0, ), _superstruct.string.call(void 0, )])); +var JsonRpcErrorStruct = object({ + code: _superstruct.integer.call(void 0, ), + message: _superstruct.string.call(void 0, ), + data: exactOptional(JsonStruct), + stack: exactOptional(_superstruct.string.call(void 0, )) +}); +var JsonRpcParamsStruct = _superstruct.union.call(void 0, [_superstruct.record.call(void 0, _superstruct.string.call(void 0, ), JsonStruct), _superstruct.array.call(void 0, JsonStruct)]); +var JsonRpcRequestStruct = object({ + id: JsonRpcIdStruct, + jsonrpc: JsonRpcVersionStruct, + method: _superstruct.string.call(void 0, ), + params: exactOptional(JsonRpcParamsStruct) +}); +var JsonRpcNotificationStruct = object({ + jsonrpc: JsonRpcVersionStruct, + method: _superstruct.string.call(void 0, ), + params: exactOptional(JsonRpcParamsStruct) +}); +function isJsonRpcNotification(value) { + return _superstruct.is.call(void 0, value, JsonRpcNotificationStruct); +} +function assertIsJsonRpcNotification(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcNotificationStruct, + "Invalid JSON-RPC notification", + ErrorWrapper + ); +} +function isJsonRpcRequest(value) { + return _superstruct.is.call(void 0, value, JsonRpcRequestStruct); +} +function assertIsJsonRpcRequest(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcRequestStruct, + "Invalid JSON-RPC request", + ErrorWrapper + ); +} +var PendingJsonRpcResponseStruct = _superstruct.object.call(void 0, { + id: JsonRpcIdStruct, + jsonrpc: JsonRpcVersionStruct, + result: _superstruct.optional.call(void 0, _superstruct.unknown.call(void 0, )), + error: _superstruct.optional.call(void 0, JsonRpcErrorStruct) +}); +var JsonRpcSuccessStruct = object({ + id: JsonRpcIdStruct, + jsonrpc: JsonRpcVersionStruct, + result: JsonStruct +}); +var JsonRpcFailureStruct = object({ + id: JsonRpcIdStruct, + jsonrpc: JsonRpcVersionStruct, + error: JsonRpcErrorStruct +}); +var JsonRpcResponseStruct = _superstruct.union.call(void 0, [ + JsonRpcSuccessStruct, + JsonRpcFailureStruct +]); +function isPendingJsonRpcResponse(response) { + return _superstruct.is.call(void 0, response, PendingJsonRpcResponseStruct); +} +function assertIsPendingJsonRpcResponse(response, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + response, + PendingJsonRpcResponseStruct, + "Invalid pending JSON-RPC response", + ErrorWrapper + ); +} +function isJsonRpcResponse(response) { + return _superstruct.is.call(void 0, response, JsonRpcResponseStruct); +} +function assertIsJsonRpcResponse(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcResponseStruct, + "Invalid JSON-RPC response", + ErrorWrapper + ); +} +function isJsonRpcSuccess(value) { + return _superstruct.is.call(void 0, value, JsonRpcSuccessStruct); +} +function assertIsJsonRpcSuccess(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcSuccessStruct, + "Invalid JSON-RPC success response", + ErrorWrapper + ); +} +function isJsonRpcFailure(value) { + return _superstruct.is.call(void 0, value, JsonRpcFailureStruct); +} +function assertIsJsonRpcFailure(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcFailureStruct, + "Invalid JSON-RPC failure response", + ErrorWrapper + ); +} +function isJsonRpcError(value) { + return _superstruct.is.call(void 0, value, JsonRpcErrorStruct); +} +function assertIsJsonRpcError(value, ErrorWrapper) { + _chunk6ZDHSOUVjs.assertStruct.call(void 0, + value, + JsonRpcErrorStruct, + "Invalid JSON-RPC error", + ErrorWrapper + ); +} +function getJsonRpcIdValidator(options) { + const { permitEmptyString, permitFractions, permitNull } = { + permitEmptyString: true, + permitFractions: false, + permitNull: true, + ...options + }; + const isValidJsonRpcId = (id) => { + return Boolean( + typeof id === "number" && (permitFractions || Number.isInteger(id)) || typeof id === "string" && (permitEmptyString || id.length > 0) || permitNull && id === null + ); + }; + return isValidJsonRpcId; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +exports.object = object; exports.exactOptional = exactOptional; exports.UnsafeJsonStruct = UnsafeJsonStruct; exports.JsonStruct = JsonStruct; exports.isValidJson = isValidJson; exports.getSafeJson = getSafeJson; exports.getJsonSize = getJsonSize; exports.jsonrpc2 = jsonrpc2; exports.JsonRpcVersionStruct = JsonRpcVersionStruct; exports.JsonRpcIdStruct = JsonRpcIdStruct; exports.JsonRpcErrorStruct = JsonRpcErrorStruct; exports.JsonRpcParamsStruct = JsonRpcParamsStruct; exports.JsonRpcRequestStruct = JsonRpcRequestStruct; exports.JsonRpcNotificationStruct = JsonRpcNotificationStruct; exports.isJsonRpcNotification = isJsonRpcNotification; exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification; exports.isJsonRpcRequest = isJsonRpcRequest; exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest; exports.PendingJsonRpcResponseStruct = PendingJsonRpcResponseStruct; exports.JsonRpcSuccessStruct = JsonRpcSuccessStruct; exports.JsonRpcFailureStruct = JsonRpcFailureStruct; exports.JsonRpcResponseStruct = JsonRpcResponseStruct; exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse; exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse; exports.isJsonRpcResponse = isJsonRpcResponse; exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse; exports.isJsonRpcSuccess = isJsonRpcSuccess; exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess; exports.isJsonRpcFailure = isJsonRpcFailure; exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure; exports.isJsonRpcError = isJsonRpcError; exports.assertIsJsonRpcError = assertIsJsonRpcError; exports.getJsonRpcIdValidator = getJsonRpcIdValidator; +//# sourceMappingURL=chunk-OLLG4H35.js.map + +/***/ }), + +/***/ 75363: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + +// src/hex.ts +var _sha3 = __webpack_require__(2214); +var _superstruct = __webpack_require__(2150); + +// src/bytes.ts +var _base = __webpack_require__(63203); +var HEX_MINIMUM_NUMBER_CHARACTER = 48; +var HEX_MAXIMUM_NUMBER_CHARACTER = 58; +var HEX_CHARACTER_OFFSET = 87; +function getPrecomputedHexValuesBuilder() { + const lookupTable = []; + return () => { + if (lookupTable.length === 0) { + for (let i = 0; i < 256; i++) { + lookupTable.push(i.toString(16).padStart(2, "0")); + } + } + return lookupTable; + }; +} +var getPrecomputedHexValues = getPrecomputedHexValuesBuilder(); +function isBytes(value) { + return value instanceof Uint8Array; +} +function assertIsBytes(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, isBytes(value), "Value must be a Uint8Array."); +} +function bytesToHex(bytes) { + assertIsBytes(bytes); + if (bytes.length === 0) { + return "0x"; + } + const lookupTable = getPrecomputedHexValues(); + const hexadecimal = new Array(bytes.length); + for (let i = 0; i < bytes.length; i++) { + hexadecimal[i] = lookupTable[bytes[i]]; + } + return add0x(hexadecimal.join("")); +} +function bytesToBigInt(bytes) { + assertIsBytes(bytes); + const hexadecimal = bytesToHex(bytes); + return BigInt(hexadecimal); +} +function bytesToSignedBigInt(bytes) { + assertIsBytes(bytes); + let value = BigInt(0); + for (const byte of bytes) { + value = (value << BigInt(8)) + BigInt(byte); + } + return BigInt.asIntN(bytes.length * 8, value); +} +function bytesToNumber(bytes) { + assertIsBytes(bytes); + const bigint = bytesToBigInt(bytes); + _chunk6ZDHSOUVjs.assert.call(void 0, + bigint <= BigInt(Number.MAX_SAFE_INTEGER), + "Number is not a safe integer. Use `bytesToBigInt` instead." + ); + return Number(bigint); +} +function bytesToString(bytes) { + assertIsBytes(bytes); + return new TextDecoder().decode(bytes); +} +function bytesToBase64(bytes) { + assertIsBytes(bytes); + return _base.base64.encode(bytes); +} +function hexToBytes(value) { + if (_optionalChain([value, 'optionalAccess', _ => _.toLowerCase, 'optionalCall', _2 => _2()]) === "0x") { + return new Uint8Array(); + } + assertIsHexString(value); + const strippedValue = remove0x(value).toLowerCase(); + const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`; + const bytes = new Uint8Array(normalizedValue.length / 2); + for (let i = 0; i < bytes.length; i++) { + const c1 = normalizedValue.charCodeAt(i * 2); + const c2 = normalizedValue.charCodeAt(i * 2 + 1); + const n1 = c1 - (c1 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET); + const n2 = c2 - (c2 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET); + bytes[i] = n1 * 16 + n2; + } + return bytes; +} +function bigIntToBytes(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); + _chunk6ZDHSOUVjs.assert.call(void 0, value >= BigInt(0), "Value must be a non-negative bigint."); + const hexadecimal = value.toString(16); + return hexToBytes(hexadecimal); +} +function bigIntFits(value, bytes) { + _chunk6ZDHSOUVjs.assert.call(void 0, bytes > 0); + const mask = value >> BigInt(31); + return !((~value & mask) + (value & ~mask) >> BigInt(bytes * 8 + ~0)); +} +function signedBigIntToBytes(value, byteLength) { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); + _chunk6ZDHSOUVjs.assert.call(void 0, typeof byteLength === "number", "Byte length must be a number."); + _chunk6ZDHSOUVjs.assert.call(void 0, byteLength > 0, "Byte length must be greater than 0."); + _chunk6ZDHSOUVjs.assert.call(void 0, + bigIntFits(value, byteLength), + "Byte length is too small to represent the given value." + ); + let numberValue = value; + const bytes = new Uint8Array(byteLength); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = Number(BigInt.asUintN(8, numberValue)); + numberValue >>= BigInt(8); + } + return bytes.reverse(); +} +function numberToBytes(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "number", "Value must be a number."); + _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative number."); + _chunk6ZDHSOUVjs.assert.call(void 0, + Number.isSafeInteger(value), + "Value is not a safe integer. Use `bigIntToBytes` instead." + ); + const hexadecimal = value.toString(16); + return hexToBytes(hexadecimal); +} +function stringToBytes(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string."); + return new TextEncoder().encode(value); +} +function base64ToBytes(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "string", "Value must be a string."); + return _base.base64.decode(value); +} +function valueToBytes(value) { + if (typeof value === "bigint") { + return bigIntToBytes(value); + } + if (typeof value === "number") { + return numberToBytes(value); + } + if (typeof value === "string") { + if (value.startsWith("0x")) { + return hexToBytes(value); + } + return stringToBytes(value); + } + if (isBytes(value)) { + return value; + } + throw new TypeError(`Unsupported value type: "${typeof value}".`); +} +function concatBytes(values) { + const normalizedValues = new Array(values.length); + let byteLength = 0; + for (let i = 0; i < values.length; i++) { + const value = valueToBytes(values[i]); + normalizedValues[i] = value; + byteLength += value.length; + } + const bytes = new Uint8Array(byteLength); + for (let i = 0, offset = 0; i < normalizedValues.length; i++) { + bytes.set(normalizedValues[i], offset); + offset += normalizedValues[i].length; + } + return bytes; +} +function createDataView(bytes) { + if (typeof Buffer !== "undefined" && bytes instanceof Buffer) { + const buffer = bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength + ); + return new DataView(buffer); + } + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); +} + +// src/hex.ts +var HexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^(?:0x)?[0-9a-f]+$/iu); +var StrictHexStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), /^0x[0-9a-f]+$/iu); +var HexAddressStruct = _superstruct.pattern.call(void 0, + _superstruct.string.call(void 0, ), + /^0x[0-9a-f]{40}$/u +); +var HexChecksumAddressStruct = _superstruct.pattern.call(void 0, + _superstruct.string.call(void 0, ), + /^0x[0-9a-fA-F]{40}$/u +); +function isHexString(value) { + return _superstruct.is.call(void 0, value, HexStruct); +} +function isStrictHexString(value) { + return _superstruct.is.call(void 0, value, StrictHexStruct); +} +function assertIsHexString(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, isHexString(value), "Value must be a hexadecimal string."); +} +function assertIsStrictHexString(value) { + _chunk6ZDHSOUVjs.assert.call(void 0, + isStrictHexString(value), + 'Value must be a hexadecimal string, starting with "0x".' + ); +} +function isValidHexAddress(possibleAddress) { + return _superstruct.is.call(void 0, possibleAddress, HexAddressStruct) || isValidChecksumAddress(possibleAddress); +} +function getChecksumAddress(address) { + _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, address, HexChecksumAddressStruct), "Invalid hex address."); + const unPrefixed = remove0x(address.toLowerCase()); + const unPrefixedHash = remove0x(bytesToHex(_sha3.keccak_256.call(void 0, unPrefixed))); + return `0x${unPrefixed.split("").map((character, nibbleIndex) => { + const hashCharacter = unPrefixedHash[nibbleIndex]; + _chunk6ZDHSOUVjs.assert.call(void 0, _superstruct.is.call(void 0, hashCharacter, _superstruct.string.call(void 0, )), "Hash shorter than address."); + return parseInt(hashCharacter, 16) > 7 ? character.toUpperCase() : character; + }).join("")}`; +} +function isValidChecksumAddress(possibleChecksum) { + if (!_superstruct.is.call(void 0, possibleChecksum, HexChecksumAddressStruct)) { + return false; + } + return getChecksumAddress(possibleChecksum) === possibleChecksum; +} +function add0x(hexadecimal) { + if (hexadecimal.startsWith("0x")) { + return hexadecimal; + } + if (hexadecimal.startsWith("0X")) { + return `0x${hexadecimal.substring(2)}`; + } + return `0x${hexadecimal}`; +} +function remove0x(hexadecimal) { + if (hexadecimal.startsWith("0x") || hexadecimal.startsWith("0X")) { + return hexadecimal.substring(2); + } + return hexadecimal; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +exports.HexStruct = HexStruct; exports.StrictHexStruct = StrictHexStruct; exports.HexAddressStruct = HexAddressStruct; exports.HexChecksumAddressStruct = HexChecksumAddressStruct; exports.isHexString = isHexString; exports.isStrictHexString = isStrictHexString; exports.assertIsHexString = assertIsHexString; exports.assertIsStrictHexString = assertIsStrictHexString; exports.isValidHexAddress = isValidHexAddress; exports.getChecksumAddress = getChecksumAddress; exports.isValidChecksumAddress = isValidChecksumAddress; exports.add0x = add0x; exports.remove0x = remove0x; exports.isBytes = isBytes; exports.assertIsBytes = assertIsBytes; exports.bytesToHex = bytesToHex; exports.bytesToBigInt = bytesToBigInt; exports.bytesToSignedBigInt = bytesToSignedBigInt; exports.bytesToNumber = bytesToNumber; exports.bytesToString = bytesToString; exports.bytesToBase64 = bytesToBase64; exports.hexToBytes = hexToBytes; exports.bigIntToBytes = bigIntToBytes; exports.signedBigIntToBytes = signedBigIntToBytes; exports.numberToBytes = numberToBytes; exports.stringToBytes = stringToBytes; exports.base64ToBytes = base64ToBytes; exports.valueToBytes = valueToBytes; exports.concatBytes = concatBytes; exports.createDataView = createDataView; +//# sourceMappingURL=chunk-QEPVHEP7.js.map + +/***/ }), + +/***/ 96526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/misc.ts +function isNonEmptyArray(value) { + return Array.isArray(value) && value.length > 0; +} +function isNullOrUndefined(value) { + return value === null || value === void 0; +} +function isObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} +var hasProperty = (objectToCheck, name) => Object.hasOwnProperty.call(objectToCheck, name); +function getKnownPropertyNames(object) { + return Object.getOwnPropertyNames(object); +} +var JsonSize = /* @__PURE__ */ ((JsonSize2) => { + JsonSize2[JsonSize2["Null"] = 4] = "Null"; + JsonSize2[JsonSize2["Comma"] = 1] = "Comma"; + JsonSize2[JsonSize2["Wrapper"] = 1] = "Wrapper"; + JsonSize2[JsonSize2["True"] = 4] = "True"; + JsonSize2[JsonSize2["False"] = 5] = "False"; + JsonSize2[JsonSize2["Quote"] = 1] = "Quote"; + JsonSize2[JsonSize2["Colon"] = 1] = "Colon"; + JsonSize2[JsonSize2["Date"] = 24] = "Date"; + return JsonSize2; +})(JsonSize || {}); +var ESCAPE_CHARACTERS_REGEXP = /"|\\|\n|\r|\t/gu; +function isPlainObject(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + let proto = value; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(value) === proto; + } catch (_) { + return false; + } +} +function isASCII(character) { + return character.charCodeAt(0) <= 127; +} +function calculateStringSize(value) { + const size = value.split("").reduce((total, character) => { + if (isASCII(character)) { + return total + 1; + } + return total + 2; + }, 0); + return size + (_nullishCoalesce(value.match(ESCAPE_CHARACTERS_REGEXP), () => ( []))).length; +} +function calculateNumberSize(value) { + return value.toString().length; +} + + + + + + + + + + + + + +exports.isNonEmptyArray = isNonEmptyArray; exports.isNullOrUndefined = isNullOrUndefined; exports.isObject = isObject; exports.hasProperty = hasProperty; exports.getKnownPropertyNames = getKnownPropertyNames; exports.JsonSize = JsonSize; exports.ESCAPE_CHARACTERS_REGEXP = ESCAPE_CHARACTERS_REGEXP; exports.isPlainObject = isPlainObject; exports.isASCII = isASCII; exports.calculateStringSize = calculateStringSize; exports.calculateNumberSize = calculateNumberSize; +//# sourceMappingURL=chunk-QVEKZRZ2.js.map + +/***/ }), + +/***/ 61305: +/***/ (() => { + +"use strict"; +//# sourceMappingURL=chunk-RKRGAFXY.js.map + +/***/ }), + +/***/ 43207: +/***/ (() => { + +"use strict"; +//# sourceMappingURL=chunk-UOTVU7OQ.js.map + +/***/ }), + +/***/ 41535: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + + +var _chunkQEPVHEP7js = __webpack_require__(75363); + + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + +// src/number.ts +var numberToHex = (value) => { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "number", "Value must be a number."); + _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative number."); + _chunk6ZDHSOUVjs.assert.call(void 0, + Number.isSafeInteger(value), + "Value is not a safe integer. Use `bigIntToHex` instead." + ); + return _chunkQEPVHEP7js.add0x.call(void 0, value.toString(16)); +}; +var bigIntToHex = (value) => { + _chunk6ZDHSOUVjs.assert.call(void 0, typeof value === "bigint", "Value must be a bigint."); + _chunk6ZDHSOUVjs.assert.call(void 0, value >= 0, "Value must be a non-negative bigint."); + return _chunkQEPVHEP7js.add0x.call(void 0, value.toString(16)); +}; +var hexToNumber = (value) => { + _chunkQEPVHEP7js.assertIsHexString.call(void 0, value); + const numberValue = parseInt(value, 16); + _chunk6ZDHSOUVjs.assert.call(void 0, + Number.isSafeInteger(numberValue), + "Value is not a safe integer. Use `hexToBigInt` instead." + ); + return numberValue; +}; +var hexToBigInt = (value) => { + _chunkQEPVHEP7js.assertIsHexString.call(void 0, value); + return BigInt(_chunkQEPVHEP7js.add0x.call(void 0, value)); +}; + + + + + + +exports.numberToHex = numberToHex; exports.bigIntToHex = bigIntToHex; exports.hexToNumber = hexToNumber; exports.hexToBigInt = hexToBigInt; +//# sourceMappingURL=chunk-VFXTVNXN.js.map + +/***/ }), + +/***/ 2489: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/caip-types.ts +var _superstruct = __webpack_require__(2150); +var CAIP_CHAIN_ID_REGEX = /^(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})$/u; +var CAIP_NAMESPACE_REGEX = /^[-a-z0-9]{3,8}$/u; +var CAIP_REFERENCE_REGEX = /^[-_a-zA-Z0-9]{1,32}$/u; +var CAIP_ACCOUNT_ID_REGEX = /^(?(?[-a-z0-9]{3,8}):(?[-_a-zA-Z0-9]{1,32})):(?[-.%a-zA-Z0-9]{1,128})$/u; +var CAIP_ACCOUNT_ADDRESS_REGEX = /^[-.%a-zA-Z0-9]{1,128}$/u; +var CaipChainIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_CHAIN_ID_REGEX); +var CaipNamespaceStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_NAMESPACE_REGEX); +var CaipReferenceStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_REFERENCE_REGEX); +var CaipAccountIdStruct = _superstruct.pattern.call(void 0, _superstruct.string.call(void 0, ), CAIP_ACCOUNT_ID_REGEX); +var CaipAccountAddressStruct = _superstruct.pattern.call(void 0, + _superstruct.string.call(void 0, ), + CAIP_ACCOUNT_ADDRESS_REGEX +); +var KnownCaipNamespace = /* @__PURE__ */ ((KnownCaipNamespace2) => { + KnownCaipNamespace2["Eip155"] = "eip155"; + return KnownCaipNamespace2; +})(KnownCaipNamespace || {}); +function isCaipChainId(value) { + return _superstruct.is.call(void 0, value, CaipChainIdStruct); +} +function isCaipNamespace(value) { + return _superstruct.is.call(void 0, value, CaipNamespaceStruct); +} +function isCaipReference(value) { + return _superstruct.is.call(void 0, value, CaipReferenceStruct); +} +function isCaipAccountId(value) { + return _superstruct.is.call(void 0, value, CaipAccountIdStruct); +} +function isCaipAccountAddress(value) { + return _superstruct.is.call(void 0, value, CaipAccountAddressStruct); +} +function parseCaipChainId(caipChainId) { + const match = CAIP_CHAIN_ID_REGEX.exec(caipChainId); + if (!_optionalChain([match, 'optionalAccess', _ => _.groups])) { + throw new Error("Invalid CAIP chain ID."); + } + return { + namespace: match.groups.namespace, + reference: match.groups.reference + }; +} +function parseCaipAccountId(caipAccountId) { + const match = CAIP_ACCOUNT_ID_REGEX.exec(caipAccountId); + if (!_optionalChain([match, 'optionalAccess', _2 => _2.groups])) { + throw new Error("Invalid CAIP account ID."); + } + return { + address: match.groups.accountAddress, + chainId: match.groups.chainId, + chain: { + namespace: match.groups.namespace, + reference: match.groups.reference + } + }; +} +function toCaipChainId(namespace, reference) { + if (!isCaipNamespace(namespace)) { + throw new Error( + `Invalid "namespace", must match: ${CAIP_NAMESPACE_REGEX.toString()}` + ); + } + if (!isCaipReference(reference)) { + throw new Error( + `Invalid "reference", must match: ${CAIP_REFERENCE_REGEX.toString()}` + ); + } + return `${namespace}:${reference}`; +} + + + + + + + + + + + + + + + + + + + + + +exports.CAIP_CHAIN_ID_REGEX = CAIP_CHAIN_ID_REGEX; exports.CAIP_NAMESPACE_REGEX = CAIP_NAMESPACE_REGEX; exports.CAIP_REFERENCE_REGEX = CAIP_REFERENCE_REGEX; exports.CAIP_ACCOUNT_ID_REGEX = CAIP_ACCOUNT_ID_REGEX; exports.CAIP_ACCOUNT_ADDRESS_REGEX = CAIP_ACCOUNT_ADDRESS_REGEX; exports.CaipChainIdStruct = CaipChainIdStruct; exports.CaipNamespaceStruct = CaipNamespaceStruct; exports.CaipReferenceStruct = CaipReferenceStruct; exports.CaipAccountIdStruct = CaipAccountIdStruct; exports.CaipAccountAddressStruct = CaipAccountAddressStruct; exports.KnownCaipNamespace = KnownCaipNamespace; exports.isCaipChainId = isCaipChainId; exports.isCaipNamespace = isCaipNamespace; exports.isCaipReference = isCaipReference; exports.isCaipAccountId = isCaipAccountId; exports.isCaipAccountAddress = isCaipAccountAddress; exports.parseCaipChainId = parseCaipChainId; exports.parseCaipAccountId = parseCaipAccountId; exports.toCaipChainId = toCaipChainId; +//# sourceMappingURL=chunk-YWAID473.js.map + +/***/ }), + +/***/ 51584: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true})); + + + +var _chunk3W5G4CYIjs = __webpack_require__(85244); + +// src/collections.ts +var _map; +var FrozenMap = class { + constructor(entries) { + _chunk3W5G4CYIjs.__privateAdd.call(void 0, this, _map, void 0); + _chunk3W5G4CYIjs.__privateSet.call(void 0, this, _map, new Map(entries)); + Object.freeze(this); + } + get size() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).size; + } + [Symbol.iterator]() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map)[Symbol.iterator](); + } + entries() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).entries(); + } + forEach(callbackfn, thisArg) { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).forEach( + (value, key, _map2) => callbackfn.call(thisArg, value, key, this) + ); + } + get(key) { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).get(key); + } + has(key) { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).has(key); + } + keys() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).keys(); + } + values() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _map).values(); + } + toString() { + return `FrozenMap(${this.size}) {${this.size > 0 ? ` ${[...this.entries()].map(([key, value]) => `${String(key)} => ${String(value)}`).join(", ")} ` : ""}}`; + } +}; +_map = new WeakMap(); +var _set; +var FrozenSet = class { + constructor(values) { + _chunk3W5G4CYIjs.__privateAdd.call(void 0, this, _set, void 0); + _chunk3W5G4CYIjs.__privateSet.call(void 0, this, _set, new Set(values)); + Object.freeze(this); + } + get size() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).size; + } + [Symbol.iterator]() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set)[Symbol.iterator](); + } + entries() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).entries(); + } + forEach(callbackfn, thisArg) { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).forEach( + (value, value2, _set2) => callbackfn.call(thisArg, value, value2, this) + ); + } + has(value) { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).has(value); + } + keys() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).keys(); + } + values() { + return _chunk3W5G4CYIjs.__privateGet.call(void 0, this, _set).values(); + } + toString() { + return `FrozenSet(${this.size}) {${this.size > 0 ? ` ${[...this.values()].map((member) => String(member)).join(", ")} ` : ""}}`; + } +}; +_set = new WeakMap(); +Object.freeze(FrozenMap); +Object.freeze(FrozenMap.prototype); +Object.freeze(FrozenSet); +Object.freeze(FrozenSet.prototype); + + + + +exports.FrozenMap = FrozenMap; exports.FrozenSet = FrozenSet; +//# sourceMappingURL=chunk-Z2RGWDD7.js.map + +/***/ }), + +/***/ 22049: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({value: true}));__webpack_require__(87982); + + + + + +var _chunkVFXTVNXNjs = __webpack_require__(41535); +__webpack_require__(58383); + + +var _chunkC6HGFEYLjs = __webpack_require__(39705); + + + + +var _chunk4RMX5YWEjs = __webpack_require__(69116); +__webpack_require__(43207); + + + + + + + + + + +var _chunk4D6XQBHAjs = __webpack_require__(73631); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var _chunkOLLG4H35js = __webpack_require__(87427); +__webpack_require__(61305); + + + +var _chunk2LBGT4GHjs = __webpack_require__(61275); + + + + + + + + + + + + + + + + + + + + +var _chunkYWAID473js = __webpack_require__(2489); + + +var _chunkE4C7EW4Rjs = __webpack_require__(1508); + + +var _chunk6NZW4WK4js = __webpack_require__(21848); + + + + + +var _chunkDHVKFDHQjs = __webpack_require__(1203); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var _chunkQEPVHEP7js = __webpack_require__(75363); + + + + + +var _chunk6ZDHSOUVjs = __webpack_require__(40932); + + + + + + +var _chunkIZC266HSjs = __webpack_require__(1486); + + + + + + + + + + + + +var _chunkQVEKZRZ2js = __webpack_require__(96526); + + + +var _chunkZ2RGWDD7js = __webpack_require__(51584); +__webpack_require__(85244); +__webpack_require__(51423); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +exports.AssertionError = _chunk6ZDHSOUVjs.AssertionError; exports.CAIP_ACCOUNT_ADDRESS_REGEX = _chunkYWAID473js.CAIP_ACCOUNT_ADDRESS_REGEX; exports.CAIP_ACCOUNT_ID_REGEX = _chunkYWAID473js.CAIP_ACCOUNT_ID_REGEX; exports.CAIP_CHAIN_ID_REGEX = _chunkYWAID473js.CAIP_CHAIN_ID_REGEX; exports.CAIP_NAMESPACE_REGEX = _chunkYWAID473js.CAIP_NAMESPACE_REGEX; exports.CAIP_REFERENCE_REGEX = _chunkYWAID473js.CAIP_REFERENCE_REGEX; exports.CaipAccountAddressStruct = _chunkYWAID473js.CaipAccountAddressStruct; exports.CaipAccountIdStruct = _chunkYWAID473js.CaipAccountIdStruct; exports.CaipChainIdStruct = _chunkYWAID473js.CaipChainIdStruct; exports.CaipNamespaceStruct = _chunkYWAID473js.CaipNamespaceStruct; exports.CaipReferenceStruct = _chunkYWAID473js.CaipReferenceStruct; exports.ChecksumStruct = _chunkE4C7EW4Rjs.ChecksumStruct; exports.Duration = _chunk4RMX5YWEjs.Duration; exports.ESCAPE_CHARACTERS_REGEXP = _chunkQVEKZRZ2js.ESCAPE_CHARACTERS_REGEXP; exports.FrozenMap = _chunkZ2RGWDD7js.FrozenMap; exports.FrozenSet = _chunkZ2RGWDD7js.FrozenSet; exports.HexAddressStruct = _chunkQEPVHEP7js.HexAddressStruct; exports.HexChecksumAddressStruct = _chunkQEPVHEP7js.HexChecksumAddressStruct; exports.HexStruct = _chunkQEPVHEP7js.HexStruct; exports.JsonRpcErrorStruct = _chunkOLLG4H35js.JsonRpcErrorStruct; exports.JsonRpcFailureStruct = _chunkOLLG4H35js.JsonRpcFailureStruct; exports.JsonRpcIdStruct = _chunkOLLG4H35js.JsonRpcIdStruct; exports.JsonRpcNotificationStruct = _chunkOLLG4H35js.JsonRpcNotificationStruct; exports.JsonRpcParamsStruct = _chunkOLLG4H35js.JsonRpcParamsStruct; exports.JsonRpcRequestStruct = _chunkOLLG4H35js.JsonRpcRequestStruct; exports.JsonRpcResponseStruct = _chunkOLLG4H35js.JsonRpcResponseStruct; exports.JsonRpcSuccessStruct = _chunkOLLG4H35js.JsonRpcSuccessStruct; exports.JsonRpcVersionStruct = _chunkOLLG4H35js.JsonRpcVersionStruct; exports.JsonSize = _chunkQVEKZRZ2js.JsonSize; exports.JsonStruct = _chunkOLLG4H35js.JsonStruct; exports.KnownCaipNamespace = _chunkYWAID473js.KnownCaipNamespace; exports.PendingJsonRpcResponseStruct = _chunkOLLG4H35js.PendingJsonRpcResponseStruct; exports.StrictHexStruct = _chunkQEPVHEP7js.StrictHexStruct; exports.UnsafeJsonStruct = _chunkOLLG4H35js.UnsafeJsonStruct; exports.VersionRangeStruct = _chunk4D6XQBHAjs.VersionRangeStruct; exports.VersionStruct = _chunk4D6XQBHAjs.VersionStruct; exports.add0x = _chunkQEPVHEP7js.add0x; exports.assert = _chunk6ZDHSOUVjs.assert; exports.assertExhaustive = _chunk6ZDHSOUVjs.assertExhaustive; exports.assertIsBytes = _chunkQEPVHEP7js.assertIsBytes; exports.assertIsHexString = _chunkQEPVHEP7js.assertIsHexString; exports.assertIsJsonRpcError = _chunkOLLG4H35js.assertIsJsonRpcError; exports.assertIsJsonRpcFailure = _chunkOLLG4H35js.assertIsJsonRpcFailure; exports.assertIsJsonRpcNotification = _chunkOLLG4H35js.assertIsJsonRpcNotification; exports.assertIsJsonRpcRequest = _chunkOLLG4H35js.assertIsJsonRpcRequest; exports.assertIsJsonRpcResponse = _chunkOLLG4H35js.assertIsJsonRpcResponse; exports.assertIsJsonRpcSuccess = _chunkOLLG4H35js.assertIsJsonRpcSuccess; exports.assertIsPendingJsonRpcResponse = _chunkOLLG4H35js.assertIsPendingJsonRpcResponse; exports.assertIsSemVerRange = _chunk4D6XQBHAjs.assertIsSemVerRange; exports.assertIsSemVerVersion = _chunk4D6XQBHAjs.assertIsSemVerVersion; exports.assertIsStrictHexString = _chunkQEPVHEP7js.assertIsStrictHexString; exports.assertStruct = _chunk6ZDHSOUVjs.assertStruct; exports.base64 = _chunk6NZW4WK4js.base64; exports.base64ToBytes = _chunkQEPVHEP7js.base64ToBytes; exports.bigIntToBytes = _chunkQEPVHEP7js.bigIntToBytes; exports.bigIntToHex = _chunkVFXTVNXNjs.bigIntToHex; exports.bytesToBase64 = _chunkQEPVHEP7js.bytesToBase64; exports.bytesToBigInt = _chunkQEPVHEP7js.bytesToBigInt; exports.bytesToHex = _chunkQEPVHEP7js.bytesToHex; exports.bytesToNumber = _chunkQEPVHEP7js.bytesToNumber; exports.bytesToSignedBigInt = _chunkQEPVHEP7js.bytesToSignedBigInt; exports.bytesToString = _chunkQEPVHEP7js.bytesToString; exports.calculateNumberSize = _chunkQVEKZRZ2js.calculateNumberSize; exports.calculateStringSize = _chunkQVEKZRZ2js.calculateStringSize; exports.concatBytes = _chunkQEPVHEP7js.concatBytes; exports.createBigInt = _chunkDHVKFDHQjs.createBigInt; exports.createBytes = _chunkDHVKFDHQjs.createBytes; exports.createDataView = _chunkQEPVHEP7js.createDataView; exports.createDeferredPromise = _chunkC6HGFEYLjs.createDeferredPromise; exports.createHex = _chunkDHVKFDHQjs.createHex; exports.createModuleLogger = _chunk2LBGT4GHjs.createModuleLogger; exports.createNumber = _chunkDHVKFDHQjs.createNumber; exports.createProjectLogger = _chunk2LBGT4GHjs.createProjectLogger; exports.exactOptional = _chunkOLLG4H35js.exactOptional; exports.getChecksumAddress = _chunkQEPVHEP7js.getChecksumAddress; exports.getErrorMessage = _chunkIZC266HSjs.getErrorMessage; exports.getJsonRpcIdValidator = _chunkOLLG4H35js.getJsonRpcIdValidator; exports.getJsonSize = _chunkOLLG4H35js.getJsonSize; exports.getKnownPropertyNames = _chunkQVEKZRZ2js.getKnownPropertyNames; exports.getSafeJson = _chunkOLLG4H35js.getSafeJson; exports.gtRange = _chunk4D6XQBHAjs.gtRange; exports.gtVersion = _chunk4D6XQBHAjs.gtVersion; exports.hasProperty = _chunkQVEKZRZ2js.hasProperty; exports.hexToBigInt = _chunkVFXTVNXNjs.hexToBigInt; exports.hexToBytes = _chunkQEPVHEP7js.hexToBytes; exports.hexToNumber = _chunkVFXTVNXNjs.hexToNumber; exports.inMilliseconds = _chunk4RMX5YWEjs.inMilliseconds; exports.isASCII = _chunkQVEKZRZ2js.isASCII; exports.isBytes = _chunkQEPVHEP7js.isBytes; exports.isCaipAccountAddress = _chunkYWAID473js.isCaipAccountAddress; exports.isCaipAccountId = _chunkYWAID473js.isCaipAccountId; exports.isCaipChainId = _chunkYWAID473js.isCaipChainId; exports.isCaipNamespace = _chunkYWAID473js.isCaipNamespace; exports.isCaipReference = _chunkYWAID473js.isCaipReference; exports.isErrorWithCode = _chunkIZC266HSjs.isErrorWithCode; exports.isErrorWithMessage = _chunkIZC266HSjs.isErrorWithMessage; exports.isErrorWithStack = _chunkIZC266HSjs.isErrorWithStack; exports.isHexString = _chunkQEPVHEP7js.isHexString; exports.isJsonRpcError = _chunkOLLG4H35js.isJsonRpcError; exports.isJsonRpcFailure = _chunkOLLG4H35js.isJsonRpcFailure; exports.isJsonRpcNotification = _chunkOLLG4H35js.isJsonRpcNotification; exports.isJsonRpcRequest = _chunkOLLG4H35js.isJsonRpcRequest; exports.isJsonRpcResponse = _chunkOLLG4H35js.isJsonRpcResponse; exports.isJsonRpcSuccess = _chunkOLLG4H35js.isJsonRpcSuccess; exports.isNonEmptyArray = _chunkQVEKZRZ2js.isNonEmptyArray; exports.isNullOrUndefined = _chunkQVEKZRZ2js.isNullOrUndefined; exports.isObject = _chunkQVEKZRZ2js.isObject; exports.isPendingJsonRpcResponse = _chunkOLLG4H35js.isPendingJsonRpcResponse; exports.isPlainObject = _chunkQVEKZRZ2js.isPlainObject; exports.isStrictHexString = _chunkQEPVHEP7js.isStrictHexString; exports.isValidChecksumAddress = _chunkQEPVHEP7js.isValidChecksumAddress; exports.isValidHexAddress = _chunkQEPVHEP7js.isValidHexAddress; exports.isValidJson = _chunkOLLG4H35js.isValidJson; exports.isValidSemVerRange = _chunk4D6XQBHAjs.isValidSemVerRange; exports.isValidSemVerVersion = _chunk4D6XQBHAjs.isValidSemVerVersion; exports.jsonrpc2 = _chunkOLLG4H35js.jsonrpc2; exports.numberToBytes = _chunkQEPVHEP7js.numberToBytes; exports.numberToHex = _chunkVFXTVNXNjs.numberToHex; exports.object = _chunkOLLG4H35js.object; exports.parseCaipAccountId = _chunkYWAID473js.parseCaipAccountId; exports.parseCaipChainId = _chunkYWAID473js.parseCaipChainId; exports.remove0x = _chunkQEPVHEP7js.remove0x; exports.satisfiesVersionRange = _chunk4D6XQBHAjs.satisfiesVersionRange; exports.signedBigIntToBytes = _chunkQEPVHEP7js.signedBigIntToBytes; exports.stringToBytes = _chunkQEPVHEP7js.stringToBytes; exports.timeSince = _chunk4RMX5YWEjs.timeSince; exports.toCaipChainId = _chunkYWAID473js.toCaipChainId; exports.valueToBytes = _chunkQEPVHEP7js.valueToBytes; exports.wrapError = _chunkIZC266HSjs.wrapError; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 82102: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = exports.isBytes = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`boolean expected, not ${b}`); +} +exports.bool = bool; +// copied from utils +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +exports.isBytes = isBytes; +function bytes(b, ...lengths) { + if (!isBytes(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}`); +} +exports.bytes = bytes; +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); +} +exports.hash = hash; +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'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports["default"] = assert; +//# sourceMappingURL=_assert.js.map + +/***/ }), + +/***/ 17335: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports["default"] = u64; +//# sourceMappingURL=_u64.js.map + +/***/ }), + +/***/ 6256: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map + +/***/ }), + +/***/ 2214: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = __webpack_require__(82102); +const _u64_js_1 = __webpack_require__(17335); +const utils_js_1 = __webpack_require__(79520); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); + keccakP(this.state32, this.rounds); + if (!utils_js_1.isLE) + (0, utils_js_1.byteSwap32)(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map + +/***/ }), + +/***/ 79520: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.byteSwap32 = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = exports.isBytes = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const crypto_1 = __webpack_require__(6256); +const _assert_js_1 = __webpack_require__(82102); +// export { isBytes } from './_assert.js'; +// We can't reuse isBytes from _assert, because somehow this causes huge perf issues +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +exports.isBytes = isBytes; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +exports.rotl = rotl; +exports.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); +exports.byteSwap = byteSwap; +// Conditionally byte swap if on a big-endian platform +exports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = (0, exports.byteSwap)(arr[i]); + } +} +exports.byteSwap32 = byteSwap32; +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + (0, _assert_js_1.bytes)(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(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(hex.charCodeAt(hi)); + const n2 = asciiToBase16(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; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(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 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * 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(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + (0, _assert_js_1.bytes)(data); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + (0, _assert_js_1.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; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 73562: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createCurve = exports.getHash = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const hmac_1 = __webpack_require__(39615); +const utils_1 = __webpack_require__(99175); +const weierstrass_js_1 = __webpack_require__(91705); +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)), + randomBytes: utils_1.randomBytes, + }; +} +exports.getHash = getHash; +function createCurve(curveDef, defHash) { + const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +exports.createCurve = createCurve; +//# sourceMappingURL=_shortw_utils.js.map + +/***/ }), + +/***/ 62422: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateBasic = exports.wNAF = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const modular_js_1 = __webpack_require__(24967); +const utils_js_1 = __webpack_require__(91484); +const _0n = BigInt(0); +const _1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +exports.wNAF = wNAF; +function validateBasic(curve) { + (0, modular_js_1.validateField)(curve.Fp); + (0, utils_js_1.validateObject)(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +exports.validateBasic = validateBasic; +//# sourceMappingURL=curve.js.map + +/***/ }), + +/***/ 71761: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0; +const modular_js_1 = __webpack_require__(24967); +const utils_js_1 = __webpack_require__(91484); +function validateDST(dst) { + if ((0, utils_js_1.isBytes)(dst)) + return dst; + if (typeof dst === 'string') + return (0, utils_js_1.utf8ToBytes)(dst); + throw new Error('DST must be Uint8Array or string'); +} +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = utils_js_1.bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE) +function i2osp(value, length) { + if (value < 0 || value >= 1 << (8 * length)) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function abytes(item) { + if (!(0, utils_js_1.isBytes)(item)) + throw new Error('Uint8Array expected'); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error('number expected'); +} +// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 +function expand_message_xmd(msg, DST, lenInBytes, H) { + abytes(msg); + abytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) + DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error('Invalid xmd length'); + const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H((0, utils_js_1.concatBytes)(...args)); + } + const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +exports.expand_message_xmd = expand_message_xmd; +// Produces a uniformly random byte string using an extendable-output function (XOF) H. +// 1. The collision resistance of H MUST be at least k bits. +// 2. H MUST be an XOF that has been proved indifferentiable from +// a random oracle under a reasonable cryptographic assumption. +// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 +function expand_message_xof(msg, DST, lenInBytes, k, H) { + abytes(msg); + abytes(DST); + isNum(lenInBytes); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8)); + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +exports.expand_message_xof = expand_message_xof; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F + * https://www.rfc-editor.org/rfc/rfc9380#section-5.2 + * @param msg a byte string containing the message to hash + * @param count the number of elements of F to output + * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above + * @returns [u_0, ..., u_(count - 1)], a list of field elements. + */ +function hash_to_field(msg, count, options) { + (0, utils_js_1.validateObject)(options, { + DST: 'stringOrUint8Array', + p: 'bigint', + m: 'isSafeInteger', + k: 'isSafeInteger', + hash: 'hash', + }); + const { p, k, m, hash, expand, DST: _DST } = options; + abytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = (0, modular_js_1.mod)(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +exports.hash_to_field = hash_to_field; +function isogenyMap(field, map) { + // Make same order as in spec + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); // xNum / xDen + y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev) + return { x, y }; + }; +} +exports.isogenyMap = isogenyMap; +function createHasher(Point, mapToCurve, def) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point.fromAffine(mapToCurve(u[0])); + const u1 = Point.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + }; +} +exports.createHasher = createHasher; +//# sourceMappingURL=hash-to-curve.js.map + +/***/ }), + +/***/ 24967: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mapHashToField = exports.getMinHashLength = exports.getFieldBytesLength = exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +const utils_js_1 = __webpack_require__(91484); +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n ? result : b + result; +} +exports.mod = mod; +/** + * 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(num, power, modulo) { + if (modulo <= _0n || power < _0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n) + return _0n; + let res = _1n; + while (power > _0n) { + if (power & _1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n; + } + return res; +} +exports.pow = pow; +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +exports.pow2 = pow2; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n || modulo <= _0n) { + 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(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +exports.invert = invert; +/** + * 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(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) / _2n; + 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, S = 0; Q % _2n === _0n; Q /= _2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n) / _4n; + 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) / _2n; + 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 << 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; + }; +} +exports.tonelliShanks = tonelliShanks; +function FpSqrt(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 === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n) / _4n; + 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 === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n), 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; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +exports.FpSqrt = FpSqrt; +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +exports.isNegativeLE = isNegativeLE; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return (0, utils_js_1.validateObject)(field, opts); +} +exports.validateField = validateField; +// 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(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n) + throw new Error('Expected power > 0'); + if (power === _0n) + return f.ONE; + if (power === _1n) + return num; + let p = f.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n; + } + return p; +} +exports.FpPow = FpPow; +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(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; +} +exports.FpInvertBatch = FpInvertBatch; +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +exports.FpDiv = FpDiv; +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +exports.FpIsSquare = FpIsSquare; +// CURVE.n lengths +function nLength(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 }; +} +exports.nLength = nLength; +/** + * 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(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: (0, utils_js_1.bitMask)(BITS), + ZERO: _0n, + ONE: _1n, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n, + isOdd: (num) => (num & _1n) === _1n, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(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(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(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 ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); + }, + }); + return Object.freeze(f); +} +exports.Field = Field; +function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +exports.FpSqrtOdd = FpSqrtOdd; +function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +exports.FpSqrtEven = FpSqrtEven; +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = (0, utils_js_1.ensureBytes)('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); + return mod(num, groupOrder - _1n) + _1n; +} +exports.hashToPrivateScalar = hashToPrivateScalar; +/** + * 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') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +exports.getFieldBytesLength = getFieldBytesLength; +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +exports.getMinHashLength = getMinHashLength; +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? (0, utils_js_1.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen); +} +exports.mapHashToField = mapHashToField; +//# sourceMappingURL=modular.js.map + +/***/ }), + +/***/ 91484: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = exports.isBytes = void 0; +/*! 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 = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +exports.isBytes = isBytes; +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!isBytes(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +exports.numberToHexUnpadded = numberToHexUnpadded; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +exports.hexToNumber = hexToNumber; +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(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(hex.charCodeAt(hi)); + const n2 = asciiToBase16(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; +} +exports.hexToBytes = hexToBytes; +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +exports.bytesToNumberBE = bytesToNumberBE; +function bytesToNumberLE(bytes) { + if (!isBytes(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +exports.bytesToNumberLE = bytesToNumberLE; +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +exports.numberToBytesBE = numberToBytesBE; +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +exports.numberToBytesLE = numberToBytesLE; +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +exports.numberToVarBytesBE = numberToVarBytesBE; +/** + * 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(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(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; +} +exports.ensureBytes = ensureBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + if (!isBytes(a)) + throw new Error('Uint8Array expected'); + sum += a.length; + } + let res = new Uint8Array(sum); + let pad = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +exports.concatBytes = concatBytes; +// 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; +} +exports.equalBytes = equalBytes; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(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 +} +exports.utf8ToBytes = utf8ToBytes; +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +exports.bitLen = bitLen; +/** + * 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; +} +exports.bitGet = bitGet; +/** + * Sets single bit at position. + */ +const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); +}; +exports.bitSet = bitSet; +/** + * 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 = (n) => (_2n << BigInt(n - 1)) - _1n; +exports.bitMask = bitMask; +// 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(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(...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; +} +exports.createHmacDrbg = createHmacDrbg; +// Validating curves and fields +const validatorFns = { + 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(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 = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[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; +} +exports.validateObject = validateObject; +// 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' }); +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 91705: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +const mod = __webpack_require__(24967); +const ut = __webpack_require__(91484); +const utils_js_1 = __webpack_require__(91484); +const curve_js_1 = __webpack_require__(62422); +function validatePointOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +exports.DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = exports.DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = exports.DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!ut.isBytes(data)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (ut.isBytes(key)) + key = ut.bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod.mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) + return I; + assertGE(n); // Will throw on 0 + if (n === _1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return ut.bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +exports.weierstrassPoints = weierstrassPoints; +function validateOpts(curve) { + const opts = (0, curve_js_1.validateBasic)(curve); + ut.validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return mod.mod(a, CURVE_ORDER); + } + function invN(a) { + return mod.invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = ut.concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = ut.bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & _1n) === _1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return ut.hexToBytes(this.toDERHex()); + } + toDERHex() { + return exports.DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return ut.hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = mod.getMinHashLength(CURVE.n); + return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = ut.isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = ut.bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = ut.bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return ut.numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + if (prehash) + msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e)); // check for being bytes + } + const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash); + publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || ut.isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof exports.DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +exports.weierstrass = weierstrass; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +exports.SWUFpSqrtRatio = SWUFpSqrtRatio; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +function mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; +//# sourceMappingURL=weierstrass.js.map + +/***/ }), + +/***/ 8510: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sha256_1 = __webpack_require__(22623); +const utils_1 = __webpack_require__(99175); +const modular_js_1 = __webpack_require__(24967); +const weierstrass_js_1 = __webpack_require__(91705); +const utils_js_1 = __webpack_require__(91484); +const hash_to_curve_js_1 = __webpack_require__(71761); +const _shortw_utils_js_1 = __webpack_require__(73562); +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P; + const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P; + const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P; + const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P; + const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P; + const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P; + const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P; + const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P; + const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P; + const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P; + const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P; + const root = (0, modular_js_1.pow2)(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n); + let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256_1.sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const _0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = (0, utils_js_1.concatBytes)(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32); +const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P); +const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N); +const Point = exports.secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % _2n !== _0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) { + const m = (0, utils_js_1.ensureBytes)('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n + if (k_ === _0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64); + const m = (0, utils_js_1.ensureBytes)('message', message); + const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32); + try { + const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails + const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +exports.schnorr = (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: exports.secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE: utils_js_1.numberToBytesBE, + bytesToNumberBE: utils_js_1.bytesToNumberBE, + taggedHash, + mod: modular_js_1.mod, + }, +}))(); +const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.isogenyMap)(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))(); +const htf = /* @__PURE__ */ (() => (0, hash_to_curve_js_1.createHasher)(exports.secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256_1.sha256, +}))(); +exports.hashToCurve = (() => htf.hashToCurve)(); +exports.encodeToCurve = (() => htf.encodeToCurve)(); +//# sourceMappingURL=secp256k1.js.map + +/***/ }), + +/***/ 67557: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +// copied from utils +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +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'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { number, bool, bytes, hash, exists, output }; +exports["default"] = assert; +//# sourceMappingURL=_assert.js.map + +/***/ }), + +/***/ 90915: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SHA2 = void 0; +const _assert_js_1 = __webpack_require__(67557); +const utils_js_1 = __webpack_require__(99175); +// Polyfill for Safari 14 +function setBigUint64(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); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + 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 = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + (0, _assert_js_1.exists)(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(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 = (0, utils_js_1.createView)(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) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.output)(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(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(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; + } +} +exports.SHA2 = SHA2; +//# sourceMappingURL=_sha2.js.map + +/***/ }), + +/***/ 22318: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0; +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +exports.fromBig = fromBig; +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +exports.split = split; +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +exports.toBig = toBig; +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +exports.shrSH = shrSH; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.shrSL = shrSL; +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +exports.rotrSH = rotrSH; +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +exports.rotrSL = rotrSL; +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +exports.rotrBH = rotrBH; +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +exports.rotrBL = rotrBL; +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +exports.rotr32H = rotr32H; +const rotr32L = (h, _l) => h; +exports.rotr32L = rotr32L; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +exports.rotlSH = rotlSH; +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +exports.rotlSL = rotlSL; +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +exports.rotlBH = rotlBH; +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +exports.rotlBL = rotlBL; +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +exports.add = add; +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +exports.add3L = add3L; +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +exports.add3H = add3H; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +exports.add4L = add4L; +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +exports.add4H = add4H; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +exports.add5L = add5L; +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +exports.add5H = add5H; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +exports["default"] = u64; +//# sourceMappingURL=_u64.js.map + +/***/ }), + +/***/ 25145: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map + +/***/ }), + +/***/ 39615: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = __webpack_require__(67557); +const utils_js_1 = __webpack_require__(99175); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0, _assert_js_1.hash)(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + (0, _assert_js_1.exists)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0, _assert_js_1.exists)(this); + (0, _assert_js_1.bytes)(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map + +/***/ }), + +/***/ 22623: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = __webpack_require__(90915); +const utils_js_1 = __webpack_require__(99175); +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// 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); +// 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 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 _sha2_js_1.SHA2 { + 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 = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = 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 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.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 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.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); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); +//# sourceMappingURL=sha256.js.map + +/***/ }), + +/***/ 32955: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = exports.keccakP = void 0; +const _assert_js_1 = __webpack_require__(67557); +const _u64_js_1 = __webpack_require__(22318); +const utils_js_1 = __webpack_require__(99175); +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +exports.keccakP = keccakP; +class Keccak extends utils_js_1.Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0, _assert_js_1.number)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0, utils_js_1.u32)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0, _assert_js_1.exists)(this); + const { blockLen, state } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0, _assert_js_1.exists)(this, false); + (0, _assert_js_1.bytes)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0, _assert_js_1.number)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0, _assert_js_1.output)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +exports.Keccak = Keccak; +const gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen)); +exports.sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +exports.sha3_256 = gen(0x06, 136, 256 / 8); +exports.sha3_384 = gen(0x06, 104, 384 / 8); +exports.sha3_512 = gen(0x06, 72, 512 / 8); +exports.keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +exports.keccak_256 = gen(0x01, 136, 256 / 8); +exports.keccak_384 = gen(0x01, 104, 384 / 8); +exports.keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +exports.shake128 = genShake(0x1f, 168, 128 / 8); +exports.shake256 = genShake(0x1f, 136, 256 / 8); +//# sourceMappingURL=sha3.js.map + +/***/ }), + +/***/ 99175: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const crypto_1 = __webpack_require__(25145); +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +// Other libraries would silently corrupt the data instead of throwing an error, +// when they don't support it. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!isBytes(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(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(hex.charCodeAt(hi)); + const n2 = asciiToBase16(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; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(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 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * 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(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!isBytes(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + if (!isBytes(a)) + throw new Error('Uint8Array expected'); + 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; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 63203: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.createBase58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64nopad = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; +// Utilities +/** + * @__NO_SIDE_EFFECTS__ + */ +function assertNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error(`Wrong integer: ${n}`); +} +exports.assertNumber = assertNumber; +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain(...args) { + const id = (a) => a; + // Wrap call in closure so JIT can inline calls + const wrap = (a, b) => (c) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = args.map((x) => x.encode).reduceRight(wrap, id); + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.map((x) => x.decode).reduce(wrap, id); + return { encode, decode }; +} +/** + * Encodes integer radix representation to array of strings using alphabet and back + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(alphabet) { + return { + encode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('alphabet.encode input should be an array of numbers'); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet.length) + throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`); + return alphabet[i]; + }); + }, + decode: (input) => { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('alphabet.decode input should be array of strings'); + return input.map((letter) => { + if (typeof letter !== 'string') + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet.indexOf(letter); + if (index === -1) + throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`); + return index; + }); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = '') { + if (typeof separator !== 'string') + throw new Error('join separator should be string'); + return { + encode: (from) => { + if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string')) + throw new Error('join.encode input should be array of strings'); + for (let i of from) + if (typeof i !== 'string') + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== 'string') + throw new Error('join.decode input should be string'); + return to.split(separator); + }, + }; +} +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits, chr = '=') { + assertNumber(bits); + if (typeof chr !== 'string') + throw new Error('padding chr should be string'); + return { + encode(data) { + if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of data) + if (typeof i !== 'string') + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string')) + throw new Error('padding.encode input should be array of strings'); + for (let i of input) + if (typeof i !== 'string') + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error('Invalid padding: string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error('Invalid padding: string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn) { + if (typeof fn !== 'function') + throw new Error('normalize fn should be function'); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +/** + * Slow: O(n^2) time complexity + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix(data, from, to) { + // base 1 is impossible + if (from < 2) + throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); + if (to < 2) + throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); + if (!Array.isArray(data)) + throw new Error('convertRadix: data should be array'); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) + throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if (!Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry) { + throw new Error('convertRadix: carry overflow'); + } + carry = digitBase % to; + const rounded = Math.floor(digitBase / to); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!rounded) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = /* @__NO_SIDE_EFFECTS__ */ (a, b) => (!b ? a : gcd(b, a % b)); +const radix2carry = /*@__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); +/** + * Implemented with numbers, because BigInt is 5x slower + * @__NO_SIDE_EFFECTS__ + */ +function convertRadix2(data, from, to, padding) { + if (!Array.isArray(data)) + throw new Error('convertRadix2: data should be array'); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num) { + assertNumber(num); + return { + encode: (bytes) => { + if (!isBytes(bytes)) + throw new Error('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), 2 ** 8, num); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix.decode input should be array of numbers'); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; +} +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error('radix2: carry overflow'); + return { + encode: (bytes) => { + if (!isBytes(bytes)) + throw new Error('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number')) + throw new Error('radix2.decode input should be array of numbers'); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function unsafeWrapper(fn) { + if (typeof fn !== 'function') + throw new Error('unsafeWrapper fn should be function'); + return function (...args) { + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== 'function') + throw new Error('checksum fn should be function'); + return { + encode(data) { + if (!isBytes(data)) + throw new Error('checksum.encode: input should be Uint8Array'); + const checksum = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum, data.length); + return res; + }, + decode(data) { + if (!isBytes(data)) + throw new Error('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +// prettier-ignore +exports.utils = { + alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding, +}; +// RFC 4648 aka RFC 3548 +// --------------------- +exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join('')); +exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')); +exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')); +exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))); +exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')); +exports.base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')); +exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')); +exports.base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')); +// base58 code +// ----------- +const genBase58 = (abc) => chain(radix(58), alphabet(abc), join('')); +exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); +exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'); +exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'); +// xmr ver is done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. +// Block encoding significantly reduces quadratic complexity of base58. +// Data len (index) -> encoded block len +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +exports.base58xmr = { + encode(data) { + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = exports.base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}; +const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58); +exports.createBase58check = createBase58check; +// legacy export, bad name +exports.base58check = exports.createBase58check; +const BECH_ALPHABET = /* @__PURE__ */ chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +/** + * @__NO_SIDE_EFFECTS__ + */ +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding) { + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== 'string') + throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); + if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number')) + throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); + if (prefix.length === 0) + throw new TypeError(`Invalid prefix length ${prefix.length}`); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; + } + function decode(str, limit = 90) { + if (typeof str !== 'string') + throw new Error(`bech32.decode input should be string, not ${typeof str}`); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + const sepIndex = lowered.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = lowered.slice(0, sepIndex); + const data = lowered.slice(sepIndex + 1); + if (data.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(data).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!data.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + const { prefix, words } = decode(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; +} +exports.bech32 = genBech32('bech32'); +exports.bech32m = genBech32('bech32m'); +exports.utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), +}; +exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); +})); +// prettier-ignore +const CODERS = { + utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr +}; +const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; +const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!isBytes(bytes)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +exports.bytesToString = bytesToString; +exports.str = exports.bytesToString; // as in python, but for bytes only +const stringToBytes = (type, str) => { + if (!CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +exports.stringToBytes = stringToBytes; +exports.bytes = exports.stringToBytes; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7736: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} +exports.BaseTree = BaseTree; + + +/***/ }), + +/***/ 9093: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class MerkleTree extends BaseTree_1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports["default"] = MerkleTree; + + +/***/ }), + +/***/ 91230: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports.PartialMerkleTree = PartialMerkleTree; + + +/***/ }), + +/***/ 41217: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; +const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); +Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); +var PartialMerkleTree_1 = __webpack_require__(91230); +Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); +var simpleHash_1 = __webpack_require__(5319); +Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); +exports["default"] = FixedMerkleTree_1.default; + + +/***/ }), + +/***/ 5319: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +exports.simpleHash = simpleHash; +exports["default"] = (left, right) => simpleHash([left, right]); + + +/***/ }), + +/***/ 27351: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +/* global BigInt */ +const bigInt = __webpack_require__(92096); + +let wBigInt; + +if (typeof(BigInt) != "undefined") { + wBigInt = BigInt; + wBigInt.one = wBigInt(1); + wBigInt.zero = wBigInt(0); + + // Affine + wBigInt.genAffine = (q) => { + const nq = -q; + return (a) => { + let aux = a; + if (aux < 0) { + if (aux <= nq) { + aux = aux % q; + } + if (aux < wBigInt.zero) { + aux = aux + q; + } + } else { + if (aux >= q) { + aux = aux % q; + } + } + return aux.valueOf(); + }; + }; + + + // Inverse + wBigInt.genInverse = (q) => { + return (a) => { + let t = wBigInt.zero; + let r = q; + let newt = wBigInt.one; + let newr = wBigInt.affine(a, q); + while (newr!=wBigInt.zero) { + let q = r/newr; + [t, newt] = [newt, t-q*newt]; + [r, newr] = [newr, r-q*newr]; + } + if (t { + if (q) { + return (a,b) => (a+b) % q; + } else { + return (a,b) => a+b; + } + }; + + // Sub + wBigInt.genSub = (q) => { + if (q) { + return (a,b) => (a-b) % q; + } else { + return (a,b) => a-b; + } + }; + + + // Neg + wBigInt.genNeg = (q) => { + if (q) { + return (a) => (-a) % q; + } else { + return (a) => -a; + } + }; + + // Mul + wBigInt.genMul = (q) => { + if (q) { + return (a,b) => (a*b) % q; + } else { + return (a,b) => a*b; + } + }; + + // Shr + wBigInt.genShr = () => { + return (a,b) => a >> wBigInt(b); + }; + + // Shl + wBigInt.genShl = (q) => { + if (q) { + return (a,b) => (a << wBigInt(b)) % q; + } else { + return (a,b) => a << wBigInt(b); + } + }; + + // Equals + wBigInt.genEquals = (q) => { + if (q) { + return (a,b) => (a.affine(q) == b.affine(q)); + } else { + return (a,b) => a == b; + } + }; + + // Square + wBigInt.genSquare = (q) => { + if (q) { + return (a) => (a*a) %q; + } else { + return (a) => a*a; + } + }; + + + // Double + wBigInt.genDouble = (q) => { + if (q) { + return (a) => (a+a) %q; + } else { + return (a) => a+a; + } + }; + + // IsZero + wBigInt.genIsZero = (q) => { + if (q) { + return (a) => (a.affine(q) == wBigInt.zero); + } else { + return (a) => a == wBigInt.zero; + } + }; + + + // Other minor functions + wBigInt.prototype.isOdd = function() { + return (this & wBigInt.one) == wBigInt(1); + }; + + wBigInt.prototype.isNegative = function() { + return this < wBigInt.zero; + }; + + wBigInt.prototype.and = function(m) { + return this & m; + }; + + wBigInt.prototype.div = function(c) { + return this / c; + }; + + wBigInt.prototype.mod = function(c) { + return this % c; + }; + + wBigInt.prototype.pow = function(c) { + return this ** c; + }; + + wBigInt.prototype.abs = function() { + return (this > wBigInt.zero) ? this : -this; + }; + + wBigInt.prototype.modPow = function(e, m) { + let acc = wBigInt.one; + let exp = this; + let rem = e; + while (rem) { + if (rem & wBigInt.one) { + acc = (acc * exp) %m; + } + exp = (exp * exp) % m; + rem = rem >> wBigInt.one; + } + return acc; + }; + + wBigInt.prototype.greaterOrEquals = function(b) { + return this >= b; + }; + + wBigInt.prototype.greater = function(b) { + return this > b; + }; + wBigInt.prototype.gt = wBigInt.prototype.greater; + + wBigInt.prototype.lesserOrEquals = function(b) { + return this <= b; + }; + + wBigInt.prototype.lesser = function(b) { + return this < b; + }; + wBigInt.prototype.lt = wBigInt.prototype.lesser; + + wBigInt.prototype.equals = function(b) { + return this == b; + }; + wBigInt.prototype.eq = wBigInt.prototype.equals; + + wBigInt.prototype.neq = function(b) { + return this != b; + }; + + wBigInt.prototype.toJSNumber = function() { + return Number(this); + }; + + +} else { + + var oldProto = bigInt.prototype; + wBigInt = function(a) { + if ((typeof a == "string") && (a.slice(0,2) == "0x")) { + return bigInt(a.slice(2), 16); + } else { + return bigInt(a); + } + }; + wBigInt.one = bigInt.one; + wBigInt.zero = bigInt.zero; + wBigInt.prototype = oldProto; + + wBigInt.prototype.div = function(c) { + return this.divide(c); + }; + + // Affine + wBigInt.genAffine = (q) => { + const nq = wBigInt.zero.minus(q); + return (a) => { + let aux = a; + if (aux.isNegative()) { + if (aux.lesserOrEquals(nq)) { + aux = aux.mod(q); + } + if (aux.isNegative()) { + aux = aux.add(q); + } + } else { + if (aux.greaterOrEquals(q)) { + aux = aux.mod(q); + } + } + return aux; + }; + }; + + + // Inverse + wBigInt.genInverse = (q) => { + return (a) => a.affine(q).modInv(q); + }; + + // Add + wBigInt.genAdd = (q) => { + if (q) { + return (a,b) => { + const r = a.add(b); + return r.greaterOrEquals(q) ? r.minus(q) : r; + }; + } else { + return (a,b) => a.add(b); + } + }; + + // Sub + wBigInt.genSub = (q) => { + if (q) { + return (a,b) => a.greaterOrEquals(b) ? a.minus(b) : a.minus(b).add(q); + } else { + return (a,b) => a.minus(b); + } + }; + + wBigInt.genNeg = (q) => { + if (q) { + return (a) => a.isZero() ? a : q.minus(a); + } else { + return (a) => wBigInt.zero.minus(a); + } + }; + + // Mul + wBigInt.genMul = (q) => { + if (q) { + return (a,b) => a.times(b).mod(q); + } else { + return (a,b) => a.times(b); + } + }; + + // Shr + wBigInt.genShr = () => { + return (a,b) => a.shiftRight(wBigInt(b).value); + }; + + // Shr + wBigInt.genShl = (q) => { + if (q) { + return (a,b) => a.shiftLeft(wBigInt(b).value).mod(q); + } else { + return (a,b) => a.shiftLeft(wBigInt(b).value); + } + }; + + // Square + wBigInt.genSquare = (q) => { + if (q) { + return (a) => a.square().mod(q); + } else { + return (a) => a.square(); + } + }; + + // Double + wBigInt.genDouble = (q) => { + if (q) { + return (a) => a.add(a).mod(q); + } else { + return (a) => a.add(a); + } + }; + + // Equals + wBigInt.genEquals = (q) => { + if (q) { + return (a,b) => a.affine(q).equals(b.affine(q)); + } else { + return (a,b) => a.equals(b); + } + }; + + // IsZero + wBigInt.genIsZero = (q) => { + if (q) { + return (a) => (a.affine(q).isZero()); + } else { + return (a) => a.isZero(); + } + }; +} + + + +wBigInt.affine = function(a, q) { + return wBigInt.genAffine(q)(a); +}; + +wBigInt.prototype.affine = function (q) { + return wBigInt.affine(this, q); +}; + +wBigInt.inverse = function(a, q) { + return wBigInt.genInverse(q)(a); +}; + +wBigInt.prototype.inverse = function (q) { + return wBigInt.genInverse(q)(this); +}; + +wBigInt.add = function(a, b, q) { + return wBigInt.genAdd(q)(a,b); +}; + +wBigInt.prototype.add = function (a, q) { + return wBigInt.genAdd(q)(this, a); +}; + +wBigInt.sub = function(a, b, q) { + return wBigInt.genSub(q)(a,b); +}; + +wBigInt.prototype.sub = function (a, q) { + return wBigInt.genSub(q)(this, a); +}; + +wBigInt.neg = function(a, q) { + return wBigInt.genNeg(q)(a); +}; + +wBigInt.prototype.neg = function (q) { + return wBigInt.genNeg(q)(this); +}; + +wBigInt.mul = function(a, b, q) { + return wBigInt.genMul(q)(a,b); +}; + +wBigInt.prototype.mul = function (a, q) { + return wBigInt.genMul(q)(this, a); +}; + +wBigInt.shr = function(a, b, q) { + return wBigInt.genShr(q)(a,b); +}; + +wBigInt.prototype.shr = function (a, q) { + return wBigInt.genShr(q)(this, a); +}; + +wBigInt.shl = function(a, b, q) { + return wBigInt.genShl(q)(a,b); +}; + +wBigInt.prototype.shl = function (a, q) { + return wBigInt.genShl(q)(this, a); +}; + +wBigInt.equals = function(a, b, q) { + return wBigInt.genEquals(q)(a,b); +}; + +wBigInt.prototype.equals = function (a, q) { + return wBigInt.genEquals(q)(this, a); +}; + +wBigInt.square = function(a, q) { + return wBigInt.genSquare(q)(a); +}; + +wBigInt.prototype.square = function (q) { + return wBigInt.genSquare(q)(this); +}; + +wBigInt.double = function(a, q) { + return wBigInt.genDouble(q)(a); +}; + +wBigInt.prototype.double = function (q) { + return wBigInt.genDouble(q)(this); +}; + +wBigInt.isZero = function(a, q) { + return wBigInt.genIsZero(q)(a); +}; + +wBigInt.prototype.isZero = function (q) { + return wBigInt.genIsZero(q)(this); +}; + +wBigInt.leBuff2int = function(buff) { + let res = wBigInt.zero; + for (let i=0; i=0)) { + let c = Number(r.and(wBigInt("255"))); + buff[o] = c; + o--; + r = r.shr(8); + } + if (r.greater(wBigInt.zero)) throw new Error("Number does not feed in buffer"); + return buff; +}; + +wBigInt.prototype.beInt2Buff = function (len) { + return wBigInt.beInt2Buff(this,len); +}; + +module.exports = wBigInt; + + + +/***/ }), + +/***/ 28803: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +const bigInt = __webpack_require__(27351); + +module.exports = calculateWitness; + +function calculateWitness(circuit, inputSignals, options) { + options = options || {}; + if (!options.logFunction) options.logFunction = console.log; + const ctx = new RTCtx(circuit, options); + + function iterateSelector(values, sels, cb) { + if (!Array.isArray(values)) { + return cb(sels, values); + } + for (let i=0; i " + ctx.witness[i].toString()); + } + return ctx.witness.slice(0, circuit.nVars); +// return ctx.witness; +} + +class RTCtx { + constructor(circuit, options) { + this.options = options; + this.scopes = []; + this.circuit = circuit; + this.witness = new Array(circuit.nSignals); + this.notInitSignals = {}; + for (let c in this.circuit.components) { + this.notInitSignals[c] = this.circuit.components[c].inputSignals; + } + } + + _sels2str(sels) { + let res = ""; + for (let i=0; i { + if (this.notInitSignals[c] == 0) this.triggerComponent(c); + }); + return this.witness[sId]; + } + + setVar(name, sels, value) { + function setVarArray(a, sels2, value) { + if (sels2.length == 1) { + a[sels2[0]] = value; + } else { + if (typeof(a[sels2[0]]) == "undefined") a[sels2[0]] = []; + setVarArray(a[sels2[0]], sels2.slice(1), value); + } + } + const scope = this.scopes[this.scopes.length-1]; + if (sels.length == 0) { + scope[name] = value; + } else { + if (typeof(scope[name]) == "undefined") scope[name] = []; + setVarArray(scope[name], sels, value); + } + return value; + } + + getVar(name, sels) { + function select(a, sels2) { + return (sels2.length == 0) ? a : select(a[sels2[0]], sels2.slice(1)); + } + for (let i=this.scopes.length-1; i>=0; i--) { + if (typeof(this.scopes[i][name]) != "undefined") return select(this.scopes[i][name], sels); + } + throw new Error("Variable not defined: " + name); + } + + getSignal(name, sels) { + let fullName = name=="one" ? "one" : this.currentComponent + "." + name; + fullName += this._sels2str(sels); + return this.getSignalFullName(fullName); + } + + + getPin(componentName, componentSels, signalName, signalSels) { + let fullName = componentName=="one" ? "one" : this.currentComponent + "." + componentName; + fullName += this._sels2str(componentSels) + + "."+ + signalName+ + this._sels2str(signalSels); + return this.getSignalFullName(fullName); + } + + getSignalFullName(fullName) { + const sId = this.circuit.getSignalIdx(fullName); + if (typeof(this.witness[sId]) == "undefined") { + throw new Error("Signal not initialized: "+fullName); + } + if (this.options.logGet) this.options.logFunction("get --->" + fullName + " = " + this.witness[sId].toString() ); + return this.witness[sId]; + } + + assert(a,b,errStr) { + const ba = bigInt(a); + const bb = bigInt(b); + if (!ba.equals(bb)) { + throw new Error("Constraint doesn't match "+ this.currentComponent+": "+ errStr + " -> "+ ba.toString() + " != " + bb.toString()); + } + } +} + + +/***/ }), + +/***/ 98665: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +const bigInt = __webpack_require__(27351); + +const __P__ = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); +const __MASK__ = bigInt("28948022309329048855892746252171976963317496166410141009864396001978282409983"); // 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF +const calculateWitness = __webpack_require__(28803); + +module.exports = class Circuit { + constructor(circuitDef) { + this.nPubInputs = circuitDef.nPubInputs; + this.nPrvInputs = circuitDef.nPrvInputs; + this.nInputs = circuitDef.nInputs; + this.nOutputs = circuitDef.nOutputs; + this.nVars = circuitDef.nVars; + this.nSignals = circuitDef.nSignals; + this.nConstants = circuitDef.nConstants; + + this.nConstraints = circuitDef.constraints.length; + + this.signalName2Idx = circuitDef.signalName2Idx; + this.components = circuitDef.components; + this.componentName2Idx = circuitDef.componentName2Idx; + this.signals = circuitDef.signals; + this.constraints = circuitDef.constraints; + + this.templates = {}; + for (let t in circuitDef.templates) { + this.templates[t] = eval(" const __f= " +circuitDef.templates[t] + "\n__f"); + } + + this.functions = {}; + for (let f in circuitDef.functions) { + this.functions[f] = { + params: circuitDef.functions[f].params, + func: eval(" const __f= " +circuitDef.functions[f].func + "\n__f;") + }; + } + } + + calculateWitness(input, log) { + return calculateWitness(this, input, log); + } + + checkWitness(w) { + const evalLC = (lc, w) => { + let acc = bigInt(0); + for (let k in lc) { + acc= acc.add(bigInt(w[k]).mul(bigInt(lc[k]))).mod(__P__); + } + return acc; + } + + const checkConstraint = (ct, w) => { + const a=evalLC(ct[0],w); + const b=evalLC(ct[1],w); + const c=evalLC(ct[2],w); + const res = (a.mul(b).sub(c)).affine(__P__); + if (!res.isZero()) return false; + return true; + } + + + for (let i=0; i { + let S = ""; + for (let k in lc) { + let name = this.signals[k].names[0]; + if (name == "one") name = ""; + let v = bigInt(lc[k]); + let vs; + if (!v.lesserOrEquals(__P__.shr(bigInt(1)))) { + v = __P__.sub(v); + vs = "-"+v.toString(); + } else { + if (S!="") { + vs = "+"+v.toString(); + } else { + vs = ""; + } + if (vs!="1") { + vs = vs + v.toString();; + } + } + + S= S + " " + vs + name; + } + return S; + }; + const S = `[ ${lc2str(c[0])} ] * [ ${lc2str(c[1])} ] - [ ${lc2str(c[2])} ] = 0`; + console.log(S); + } + + printConstraints() { + for (let i=0; i=this.nOutputs) throw new Error("Accessing an invalid output: "+i); + return i+1; + } + + // returns the index of the i'th input + inputIdx(i) { + if (i>=this.nInputs) throw new Error("Accessing an invalid input: "+i); + return this.nOutputs + 1 + i; + } + + // returns the index of the i'th public input + pubInputIdx(i) { + if (i>=this.nPubInputs) throw new Error("Accessing an invalid pubInput: "+i); + return this.inputIdx(i); + } + + // returns the index of the i'th private input + prvInputIdx(i) { + if (i>=this.nPrvInputs) throw new Error("Accessing an invalid prvInput: "+i); + return this.inputIdx(this.nPubInputs + i); + } + + // returns the index of the i'th variable + varIdx(i) { + if (i>=this.nVars) throw new Error("Accessing an invalid variable: "+i); + return i; + } + + // returns the index of the i'th constant + constantIdx(i) { + if (i>=this.nConstants) throw new Error("Accessing an invalid constant: "+i); + return this.nVars + i; + } + + // returns the index of the i'th signal + signalIdx(i) { + if (i>=this.nSignls) throw new Error("Accessing an invalid signal: "+i); + return i; + } + + signalNames(i) { + return this.signals[ this.getSignalIdx(i) ].names.join(", "); + } + + a(constraint, signalIdx) { + return bigInt(this.constraints[constraint][0][signalIdx] || 0 ); + } + + b(constraint, signalIdx) { + return bigInt(this.constraints[constraint][1][signalIdx] || 0); + } + + c(constraint, signalIdx) { + return bigInt(this.constraints[constraint][2][signalIdx] || 0); + } +}; + + +/***/ }), + +/***/ 73248: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +const bigInt = __webpack_require__(27351); + +module.exports.e = stringifyBigInts; +module.exports.H = unstringifyBigInts; + +function stringifyBigInts(o) { + if ((typeof(o) == "bigint") || o.isZero !== undefined) { + return o.toString(10); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + for (let k in o) { + res[k] = stringifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + +function unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return bigInt(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + for (let k in o) { + res[k] = unstringifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + + +/***/ }), + +/***/ 71293: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; + + exports.code = new Buffer("AGFzbQEAAAABPApgAn9/AGABfwBgAX8Bf2ACf38Bf2ADf39/AX9gA39/fwBgA39+fwBgAn9+AGAEf39/fwBgBX9/f39/AAIQAQNlbnYGbWVtb3J5AgDoBwNsawABAgEDAwQEBQUGBwgFBQUAAAUFAAAAAQUFAAAFBQAAAAEFAAIBAAAFAAUAAAAIAQIAAgUICQgABQkDAAUFBQUAAgUFCAAIAgEBAAUFBQAAAAMAAgEAAAUABQAAAAgBAgACBQgJCAAFCQgIB8gJYghpbnRfY29weQAACGludF96ZXJvAAEHaW50X29uZQADCmludF9pc1plcm8AAgZpbnRfZXEABAdpbnRfZ3RlAAUHaW50X2FkZAAGB2ludF9zdWIABwppbnRfbXVsT2xkAAkHaW50X211bAAIB2ludF9kaXYADA5pbnRfaW52ZXJzZU1vZAANB2YxbV9hZGQADgdmMW1fc3ViAA8HZjFtX25lZwAQC2YxbV9tUmVkdWN0ABEHZjFtX211bAASCmYxbV9tdWxPbGQAExJmMW1fZnJvbU1vbnRnb21lcnkAFRBmMW1fdG9Nb250Z29tZXJ5ABQLZjFtX2ludmVyc2UAFghmMW1fY29weQAACGYxbV96ZXJvAAEKZjFtX2lzWmVybwACBmYxbV9lcQAEB2YxbV9vbmUAFwdmcm1fYWRkABgHZnJtX3N1YgAZB2ZybV9uZWcAGgtmcm1fbVJlZHVjdAAbB2ZybV9tdWwAHApmcm1fbXVsT2xkAB0SZnJtX2Zyb21Nb250Z29tZXJ5AB8QZnJtX3RvTW9udGdvbWVyeQAeC2ZybV9pbnZlcnNlACAIZnJtX2NvcHkAAAhmcm1femVybwABCmZybV9pc1plcm8AAgZmcm1fZXEABAdmcm1fb25lACEGZnJfYWRkABgGZnJfc3ViABkGZnJfbmVnABoGZnJfbXVsACIKZnJfaW52ZXJzZQAjB2ZyX2NvcHkAAAdmcl96ZXJvAAEGZnJfb25lACEJZnJfaXNaZXJvAAIFZnJfZXEABAlnMV9pc1plcm8AJAdnMV9jb3B5ACYHZzFfemVybwAlCWcxX2RvdWJsZQAnBmcxX2FkZAAoBmcxX25lZwApBmcxX3N1YgAqEWcxX2Zyb21Nb250Z29tZXJ5ACsPZzFfdG9Nb250Z29tZXJ5ACwJZzFfYWZmaW5lAC0OZzFfdGltZXNTY2FsYXIALgtnMV9tdWx0aWV4cAA1DGcxX211bHRpZXhwMgA5B2ZmdF9mZnQAQghmZnRfaWZmdABDEWZmdF90b01vbnRnb21lcnlOAD8TZmZ0X2Zyb21Nb250Z29tZXJ5TgA+FGZmdF9jb3B5TkludGVybGVhdmVkAD0IZmZ0X211bE4ARAhwb2xfemVybwBFD3BvbF9jb25zdHJ1Y3RMQwBGCmYybV9pc1plcm8ARwhmMm1femVybwBIB2YybV9vbmUASQhmMm1fY29weQBKB2YybV9tdWwASwdmMm1fYWRkAEwHZjJtX3N1YgBNB2YybV9uZWcAThJmMm1fZnJvbU1vbnRnb21lcnkAUBBmMm1fdG9Nb250Z29tZXJ5AE8GZjJtX2VxAFELZjJtX2ludmVyc2UAUglnMl9pc1plcm8AUwdnMl9jb3B5AFUHZzJfemVybwBUCWcyX2RvdWJsZQBWBmcyX2FkZABXBmcyX25lZwBYBmcyX3N1YgBZEWcyX2Zyb21Nb250Z29tZXJ5AFoPZzJfdG9Nb250Z29tZXJ5AFsJZzJfYWZmaW5lAFwOZzJfdGltZXNTY2FsYXIAXQtnMl9tdWx0aWV4cABkDGcyX211bHRpZXhwMgBoDHRlc3RfZjFtX211bABpD3Rlc3RfZjFtX211bE9sZABqCsfEAWsqACABIAApAwA3AwAgASAAKQMINwMIIAEgACkDEDcDECABIAApAxg3AxgLHgAgAEIANwMAIABCADcDCCAAQgA3AxAgAEIANwMYCzMAIAApAxhQBEAgACkDEFAEQCAAKQMIUARAIAApAwBQDwVBAA8LBUEADwsFQQAPC0EADwseACAAQgE3AwAgAEIANwMIIABCADcDECAAQgA3AxgLRwAgACkDGCABKQMYUQRAIAApAxAgASkDEFEEQCAAKQMIIAEpAwhRBEAgACkDACABKQMAUQ8FQQAPCwVBAA8LBUEADwtBAA8LfQAgACkDGCABKQMYVARAQQAPBSAAKQMYIAEpAxhWBEBBAQ8FIAApAxAgASkDEFQEQEEADwUgACkDECABKQMQVgRAQQEPBSAAKQMIIAEpAwhUBEBBAA8FIAApAwggASkDCFYEQEEBDwUgACkDACABKQMAWg8LCwsLCwtBAA8L1AEBAX4gADUCACABNQIAfCEDIAIgAz4CACAANQIEIAE1AgR8IANCIIh8IQMgAiADPgIEIAA1AgggATUCCHwgA0IgiHwhAyACIAM+AgggADUCDCABNQIMfCADQiCIfCEDIAIgAz4CDCAANQIQIAE1AhB8IANCIIh8IQMgAiADPgIQIAA1AhQgATUCFHwgA0IgiHwhAyACIAM+AhQgADUCGCABNQIYfCADQiCIfCEDIAIgAz4CGCAANQIcIAE1Ahx8IANCIIh8IQMgAiADPgIcIANCIIinC4wCAQF+IAA1AgAgATUCAH0hAyACIANC/////w+DPgIAIAA1AgQgATUCBH0gA0Igh3whAyACIANC/////w+DPgIEIAA1AgggATUCCH0gA0Igh3whAyACIANC/////w+DPgIIIAA1AgwgATUCDH0gA0Igh3whAyACIANC/////w+DPgIMIAA1AhAgATUCEH0gA0Igh3whAyACIANC/////w+DPgIQIAA1AhQgATUCFH0gA0Igh3whAyACIANC/////w+DPgIUIAA1AhggATUCGH0gA0Igh3whAyACIANC/////w+DPgIYIAA1AhwgATUCHH0gA0Igh3whAyACIANC/////w+DPgIcIANCIIenC48QEgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfiADQv////8PgyAANQIAIgUgATUCACIGfnwhAyAEIANCIIh8IQQgAiADPgIAIARCIIghAyAEQv////8PgyAFIAE1AgQiCH58IQQgAyAEQiCIfCEDIARC/////w+DIAA1AgQiByAGfnwhBCADIARCIIh8IQMgAiAEPgIEIANCIIghBCADQv////8PgyAFIAE1AggiCn58IQMgBCADQiCIfCEEIANC/////w+DIAcgCH58IQMgBCADQiCIfCEEIANC/////w+DIAA1AggiCSAGfnwhAyAEIANCIIh8IQQgAiADPgIIIARCIIghAyAEQv////8PgyAFIAE1AgwiDH58IQQgAyAEQiCIfCEDIARC/////w+DIAcgCn58IQQgAyAEQiCIfCEDIARC/////w+DIAkgCH58IQQgAyAEQiCIfCEDIARC/////w+DIAA1AgwiCyAGfnwhBCADIARCIIh8IQMgAiAEPgIMIANCIIghBCADQv////8PgyAFIAE1AhAiDn58IQMgBCADQiCIfCEEIANC/////w+DIAcgDH58IQMgBCADQiCIfCEEIANC/////w+DIAkgCn58IQMgBCADQiCIfCEEIANC/////w+DIAsgCH58IQMgBCADQiCIfCEEIANC/////w+DIAA1AhAiDSAGfnwhAyAEIANCIIh8IQQgAiADPgIQIARCIIghAyAEQv////8PgyAFIAE1AhQiEH58IQQgAyAEQiCIfCEDIARC/////w+DIAcgDn58IQQgAyAEQiCIfCEDIARC/////w+DIAkgDH58IQQgAyAEQiCIfCEDIARC/////w+DIAsgCn58IQQgAyAEQiCIfCEDIARC/////w+DIA0gCH58IQQgAyAEQiCIfCEDIARC/////w+DIAA1AhQiDyAGfnwhBCADIARCIIh8IQMgAiAEPgIUIANCIIghBCADQv////8PgyAFIAE1AhgiEn58IQMgBCADQiCIfCEEIANC/////w+DIAcgEH58IQMgBCADQiCIfCEEIANC/////w+DIAkgDn58IQMgBCADQiCIfCEEIANC/////w+DIAsgDH58IQMgBCADQiCIfCEEIANC/////w+DIA0gCn58IQMgBCADQiCIfCEEIANC/////w+DIA8gCH58IQMgBCADQiCIfCEEIANC/////w+DIAA1AhgiESAGfnwhAyAEIANCIIh8IQQgAiADPgIYIARCIIghAyAEQv////8PgyAFIAE1AhwiFH58IQQgAyAEQiCIfCEDIARC/////w+DIAcgEn58IQQgAyAEQiCIfCEDIARC/////w+DIAkgEH58IQQgAyAEQiCIfCEDIARC/////w+DIAsgDn58IQQgAyAEQiCIfCEDIARC/////w+DIA0gDH58IQQgAyAEQiCIfCEDIARC/////w+DIA8gCn58IQQgAyAEQiCIfCEDIARC/////w+DIBEgCH58IQQgAyAEQiCIfCEDIARC/////w+DIAA1AhwiEyAGfnwhBCADIARCIIh8IQMgAiAEPgIcIANCIIghBCADQv////8PgyAHIBR+fCEDIAQgA0IgiHwhBCADQv////8PgyAJIBJ+fCEDIAQgA0IgiHwhBCADQv////8PgyALIBB+fCEDIAQgA0IgiHwhBCADQv////8PgyANIA5+fCEDIAQgA0IgiHwhBCADQv////8PgyAPIAx+fCEDIAQgA0IgiHwhBCADQv////8PgyARIAp+fCEDIAQgA0IgiHwhBCADQv////8PgyATIAh+fCEDIAQgA0IgiHwhBCACIAM+AiAgBEIgiCEDIARC/////w+DIAkgFH58IQQgAyAEQiCIfCEDIARC/////w+DIAsgEn58IQQgAyAEQiCIfCEDIARC/////w+DIA0gEH58IQQgAyAEQiCIfCEDIARC/////w+DIA8gDn58IQQgAyAEQiCIfCEDIARC/////w+DIBEgDH58IQQgAyAEQiCIfCEDIARC/////w+DIBMgCn58IQQgAyAEQiCIfCEDIAIgBD4CJCADQiCIIQQgA0L/////D4MgCyAUfnwhAyAEIANCIIh8IQQgA0L/////D4MgDSASfnwhAyAEIANCIIh8IQQgA0L/////D4MgDyAQfnwhAyAEIANCIIh8IQQgA0L/////D4MgESAOfnwhAyAEIANCIIh8IQQgA0L/////D4MgEyAMfnwhAyAEIANCIIh8IQQgAiADPgIoIARCIIghAyAEQv////8PgyANIBR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAPIBJ+fCEEIAMgBEIgiHwhAyAEQv////8PgyARIBB+fCEEIAMgBEIgiHwhAyAEQv////8PgyATIA5+fCEEIAMgBEIgiHwhAyACIAQ+AiwgA0IgiCEEIANC/////w+DIA8gFH58IQMgBCADQiCIfCEEIANC/////w+DIBEgEn58IQMgBCADQiCIfCEEIANC/////w+DIBMgEH58IQMgBCADQiCIfCEEIAIgAz4CMCAEQiCIIQMgBEL/////D4MgESAUfnwhBCADIARCIIh8IQMgBEL/////D4MgEyASfnwhBCADIARCIIh8IQMgAiAEPgI0IANCIIghBCADQv////8PgyATIBR+fCEDIAQgA0IgiHwhBCACIAM+AjggBEIgiCEDIAIgBD4CPAv0EAEBfkEoIAA1AgAgATUCAH43AwBBKCAANQIAIAE1AgR+NwMIQSggADUCACABNQIIfjcDEEEoIAA1AgAgATUCDH43AxhBKCAANQIAIAE1AhB+NwMgQSggADUCACABNQIUfjcDKEEoIAA1AgAgATUCGH43AzBBKCAANQIAIAE1Ahx+NwM4QSggADUCBCABNQIAfjcDQEEoIAA1AgQgATUCBH43A0hBKCAANQIEIAE1Agh+NwNQQSggADUCBCABNQIMfjcDWEEoIAA1AgQgATUCEH43A2BBKCAANQIEIAE1AhR+NwNoQSggADUCBCABNQIYfjcDcEEoIAA1AgQgATUCHH43A3hBKCAANQIIIAE1AgB+NwOAAUEoIAA1AgggATUCBH43A4gBQSggADUCCCABNQIIfjcDkAFBKCAANQIIIAE1Agx+NwOYAUEoIAA1AgggATUCEH43A6ABQSggADUCCCABNQIUfjcDqAFBKCAANQIIIAE1Ahh+NwOwAUEoIAA1AgggATUCHH43A7gBQSggADUCDCABNQIAfjcDwAFBKCAANQIMIAE1AgR+NwPIAUEoIAA1AgwgATUCCH43A9ABQSggADUCDCABNQIMfjcD2AFBKCAANQIMIAE1AhB+NwPgAUEoIAA1AgwgATUCFH43A+gBQSggADUCDCABNQIYfjcD8AFBKCAANQIMIAE1Ahx+NwP4AUEoIAA1AhAgATUCAH43A4ACQSggADUCECABNQIEfjcDiAJBKCAANQIQIAE1Agh+NwOQAkEoIAA1AhAgATUCDH43A5gCQSggADUCECABNQIQfjcDoAJBKCAANQIQIAE1AhR+NwOoAkEoIAA1AhAgATUCGH43A7ACQSggADUCECABNQIcfjcDuAJBKCAANQIUIAE1AgB+NwPAAkEoIAA1AhQgATUCBH43A8gCQSggADUCFCABNQIIfjcD0AJBKCAANQIUIAE1Agx+NwPYAkEoIAA1AhQgATUCEH43A+ACQSggADUCFCABNQIUfjcD6AJBKCAANQIUIAE1Ahh+NwPwAkEoIAA1AhQgATUCHH43A/gCQSggADUCGCABNQIAfjcDgANBKCAANQIYIAE1AgR+NwOIA0EoIAA1AhggATUCCH43A5ADQSggADUCGCABNQIMfjcDmANBKCAANQIYIAE1AhB+NwOgA0EoIAA1AhggATUCFH43A6gDQSggADUCGCABNQIYfjcDsANBKCAANQIYIAE1Ahx+NwO4A0EoIAA1AhwgATUCAH43A8ADQSggADUCHCABNQIEfjcDyANBKCAANQIcIAE1Agh+NwPQA0EoIAA1AhwgATUCDH43A9gDQSggADUCHCABNQIQfjcD4ANBKCAANQIcIAE1AhR+NwPoA0EoIAA1AhwgATUCGH43A/ADQSggADUCHCABNQIcfjcD+AMgA0IgiEEoNQIAfCEDIAIgAz4CACADQiCIQSg1AgR8QSg1Agh8QSg1AkB8IQMgAiADPgIEIANCIIhBKDUCDHxBKDUCRHxBKDUCEHxBKDUCSHxBKDUCgAF8IQMgAiADPgIIIANCIIhBKDUCFHxBKDUCTHxBKDUChAF8QSg1Ahh8QSg1AlB8QSg1AogBfEEoNQLAAXwhAyACIAM+AgwgA0IgiEEoNQIcfEEoNQJUfEEoNQKMAXxBKDUCxAF8QSg1AiB8QSg1Alh8QSg1ApABfEEoNQLIAXxBKDUCgAJ8IQMgAiADPgIQIANCIIhBKDUCJHxBKDUCXHxBKDUClAF8QSg1AswBfEEoNQKEAnxBKDUCKHxBKDUCYHxBKDUCmAF8QSg1AtABfEEoNQKIAnxBKDUCwAJ8IQMgAiADPgIUIANCIIhBKDUCLHxBKDUCZHxBKDUCnAF8QSg1AtQBfEEoNQKMAnxBKDUCxAJ8QSg1AjB8QSg1Amh8QSg1AqABfEEoNQLYAXxBKDUCkAJ8QSg1AsgCfEEoNQKAA3whAyACIAM+AhggA0IgiEEoNQI0fEEoNQJsfEEoNQKkAXxBKDUC3AF8QSg1ApQCfEEoNQLMAnxBKDUChAN8QSg1Ajh8QSg1AnB8QSg1AqgBfEEoNQLgAXxBKDUCmAJ8QSg1AtACfEEoNQKIA3xBKDUCwAN8IQMgAiADPgIcIANCIIhBKDUCPHxBKDUCdHxBKDUCrAF8QSg1AuQBfEEoNQKcAnxBKDUC1AJ8QSg1AowDfEEoNQLEA3xBKDUCeHxBKDUCsAF8QSg1AugBfEEoNQKgAnxBKDUC2AJ8QSg1ApADfEEoNQLIA3whAyACIAM+AiAgA0IgiEEoNQJ8fEEoNQK0AXxBKDUC7AF8QSg1AqQCfEEoNQLcAnxBKDUClAN8QSg1AswDfEEoNQK4AXxBKDUC8AF8QSg1AqgCfEEoNQLgAnxBKDUCmAN8QSg1AtADfCEDIAIgAz4CJCADQiCIQSg1ArwBfEEoNQL0AXxBKDUCrAJ8QSg1AuQCfEEoNQKcA3xBKDUC1AN8QSg1AvgBfEEoNQKwAnxBKDUC6AJ8QSg1AqADfEEoNQLYA3whAyACIAM+AiggA0IgiEEoNQL8AXxBKDUCtAJ8QSg1AuwCfEEoNQKkA3xBKDUC3AN8QSg1ArgCfEEoNQLwAnxBKDUCqAN8QSg1AuADfCEDIAIgAz4CLCADQiCIQSg1ArwCfEEoNQL0AnxBKDUCrAN8QSg1AuQDfEEoNQL4AnxBKDUCsAN8QSg1AugDfCEDIAIgAz4CMCADQiCIQSg1AvwCfEEoNQK0A3xBKDUC7AN8QSg1ArgDfEEoNQLwA3whAyACIAM+AjQgA0IgiEEoNQK8A3xBKDUC9AN8QSg1AvgDfCEDIAIgAz4COCADQiCIQSg1AvwDfCEDIAIgAz4CPAu2AQEBfiAANQAAIAF+IQMgAiADPgAAIAA1AAQgAX4gA0IgiHwhAyACIAM+AAQgADUACCABfiADQiCIfCEDIAIgAz4ACCAANQAMIAF+IANCIIh8IQMgAiADPgAMIAA1ABAgAX4gA0IgiHwhAyACIAM+ABAgADUAFCABfiADQiCIfCEDIAIgAz4AFCAANQAYIAF+IANCIIh8IQMgAiADPgAYIAA1ABwgAX4gA0IgiHwhAyACIAM+ABwLTgIBfgF/IAAhAyADNQAAIAF8IQIgAyACPgAAIAJCIIghAgJAA0AgAlANASADQQRqIQMgAzUAACACfCECIAMgAj4AACACQiCIIQIMAAsLC7ACBwF/AX8BfwF/AX4BfgF/IAIEQCACIQUFQcgEIQULIAMEQCADIQQFQegEIQQLIAAgBBAAIAFBqAQQACAFEAFBiAUQAUEfIQZBHyEHAkADQEGoBCAHai0AACAHQQNGcg0BIAdBAWshBwwACwtBqAQgB2pBA2s1AABCAXwhCCAIQgFRBEBCAEIAgBoLAkADQAJAA0AgBCAGai0AACAGQQdGcg0BIAZBAWshBgwACwsgBCAGakEHaykAACEJIAkgCIAhCSAGIAdrQQRrIQoCQANAIAlCgICAgHCDUCAKQQBOcQ0BIAlCCIghCSAKQQFqIQoMAAsLIAlQBEAgBEGoBBAFRQ0CQgEhCUEAIQoLQagEIAlBqAUQCiAEQagFIAprIAQQBxogBSAKaiAJEAsMAAsLC7UCCwF/AX8BfwF/AX8BfwF/AX8BfwF/AX9ByAUhA0HIBRABQQAhC0HoBSEFIAFB6AUQAEGIBiEEQYgGEANBACEMQagGIQggAEGoBhAAQcgGIQZB6AYhB0HIByEKAkADQCAIEAINASAFIAggBiAHEAwgBiAEQYgHEAggCwRAIAwEQEGIByADEAUEQEGIByADIAoQBxpBACENBSADQYgHIAoQBxpBASENCwVBiAcgAyAKEAYaQQEhDQsFIAwEQEGIByADIAoQBhpBACENBSADQYgHEAUEQCADQYgHIAoQBxpBACENBUGIByADIAoQBxpBASENCwsLIAMhCSAEIQMgCiEEIAkhCiAMIQsgDSEMIAUhCSAIIQUgByEIIAkhBwwACwsgCwRAIAEgAyACEAcaBSADIAIQAAsLLAAgACABIAIQBgRAIAJB6AcgAhAHGgUgAkHoBxAFBEAgAkHoByACEAcaCwsLFwAgACABIAIQBwRAIAJB6AcgAhAGGgsLFAAgABACRQRAQegHIAAgARAHGgsLnBEDAX4BfgF+QonHmaQOIQJCACEDIAA1AgAgAn5C/////w+DIQQgADUCACADQiCIfEHoBzUCACAEfnwhAyAAIAM+AgAgADUCBCADQiCIfEHoBzUCBCAEfnwhAyAAIAM+AgQgADUCCCADQiCIfEHoBzUCCCAEfnwhAyAAIAM+AgggADUCDCADQiCIfEHoBzUCDCAEfnwhAyAAIAM+AgwgADUCECADQiCIfEHoBzUCECAEfnwhAyAAIAM+AhAgADUCFCADQiCIfEHoBzUCFCAEfnwhAyAAIAM+AhQgADUCGCADQiCIfEHoBzUCGCAEfnwhAyAAIAM+AhggADUCHCADQiCIfEHoBzUCHCAEfnwhAyAAIAM+AhxB6AggA0IgiD4CAEIAIQMgADUCBCACfkL/////D4MhBCAANQIEIANCIIh8QegHNQIAIAR+fCEDIAAgAz4CBCAANQIIIANCIIh8QegHNQIEIAR+fCEDIAAgAz4CCCAANQIMIANCIIh8QegHNQIIIAR+fCEDIAAgAz4CDCAANQIQIANCIIh8QegHNQIMIAR+fCEDIAAgAz4CECAANQIUIANCIIh8QegHNQIQIAR+fCEDIAAgAz4CFCAANQIYIANCIIh8QegHNQIUIAR+fCEDIAAgAz4CGCAANQIcIANCIIh8QegHNQIYIAR+fCEDIAAgAz4CHCAANQIgIANCIIh8QegHNQIcIAR+fCEDIAAgAz4CIEHoCCADQiCIPgIEQgAhAyAANQIIIAJ+Qv////8PgyEEIAA1AgggA0IgiHxB6Ac1AgAgBH58IQMgACADPgIIIAA1AgwgA0IgiHxB6Ac1AgQgBH58IQMgACADPgIMIAA1AhAgA0IgiHxB6Ac1AgggBH58IQMgACADPgIQIAA1AhQgA0IgiHxB6Ac1AgwgBH58IQMgACADPgIUIAA1AhggA0IgiHxB6Ac1AhAgBH58IQMgACADPgIYIAA1AhwgA0IgiHxB6Ac1AhQgBH58IQMgACADPgIcIAA1AiAgA0IgiHxB6Ac1AhggBH58IQMgACADPgIgIAA1AiQgA0IgiHxB6Ac1AhwgBH58IQMgACADPgIkQegIIANCIIg+AghCACEDIAA1AgwgAn5C/////w+DIQQgADUCDCADQiCIfEHoBzUCACAEfnwhAyAAIAM+AgwgADUCECADQiCIfEHoBzUCBCAEfnwhAyAAIAM+AhAgADUCFCADQiCIfEHoBzUCCCAEfnwhAyAAIAM+AhQgADUCGCADQiCIfEHoBzUCDCAEfnwhAyAAIAM+AhggADUCHCADQiCIfEHoBzUCECAEfnwhAyAAIAM+AhwgADUCICADQiCIfEHoBzUCFCAEfnwhAyAAIAM+AiAgADUCJCADQiCIfEHoBzUCGCAEfnwhAyAAIAM+AiQgADUCKCADQiCIfEHoBzUCHCAEfnwhAyAAIAM+AihB6AggA0IgiD4CDEIAIQMgADUCECACfkL/////D4MhBCAANQIQIANCIIh8QegHNQIAIAR+fCEDIAAgAz4CECAANQIUIANCIIh8QegHNQIEIAR+fCEDIAAgAz4CFCAANQIYIANCIIh8QegHNQIIIAR+fCEDIAAgAz4CGCAANQIcIANCIIh8QegHNQIMIAR+fCEDIAAgAz4CHCAANQIgIANCIIh8QegHNQIQIAR+fCEDIAAgAz4CICAANQIkIANCIIh8QegHNQIUIAR+fCEDIAAgAz4CJCAANQIoIANCIIh8QegHNQIYIAR+fCEDIAAgAz4CKCAANQIsIANCIIh8QegHNQIcIAR+fCEDIAAgAz4CLEHoCCADQiCIPgIQQgAhAyAANQIUIAJ+Qv////8PgyEEIAA1AhQgA0IgiHxB6Ac1AgAgBH58IQMgACADPgIUIAA1AhggA0IgiHxB6Ac1AgQgBH58IQMgACADPgIYIAA1AhwgA0IgiHxB6Ac1AgggBH58IQMgACADPgIcIAA1AiAgA0IgiHxB6Ac1AgwgBH58IQMgACADPgIgIAA1AiQgA0IgiHxB6Ac1AhAgBH58IQMgACADPgIkIAA1AiggA0IgiHxB6Ac1AhQgBH58IQMgACADPgIoIAA1AiwgA0IgiHxB6Ac1AhggBH58IQMgACADPgIsIAA1AjAgA0IgiHxB6Ac1AhwgBH58IQMgACADPgIwQegIIANCIIg+AhRCACEDIAA1AhggAn5C/////w+DIQQgADUCGCADQiCIfEHoBzUCACAEfnwhAyAAIAM+AhggADUCHCADQiCIfEHoBzUCBCAEfnwhAyAAIAM+AhwgADUCICADQiCIfEHoBzUCCCAEfnwhAyAAIAM+AiAgADUCJCADQiCIfEHoBzUCDCAEfnwhAyAAIAM+AiQgADUCKCADQiCIfEHoBzUCECAEfnwhAyAAIAM+AiggADUCLCADQiCIfEHoBzUCFCAEfnwhAyAAIAM+AiwgADUCMCADQiCIfEHoBzUCGCAEfnwhAyAAIAM+AjAgADUCNCADQiCIfEHoBzUCHCAEfnwhAyAAIAM+AjRB6AggA0IgiD4CGEIAIQMgADUCHCACfkL/////D4MhBCAANQIcIANCIIh8QegHNQIAIAR+fCEDIAAgAz4CHCAANQIgIANCIIh8QegHNQIEIAR+fCEDIAAgAz4CICAANQIkIANCIIh8QegHNQIIIAR+fCEDIAAgAz4CJCAANQIoIANCIIh8QegHNQIMIAR+fCEDIAAgAz4CKCAANQIsIANCIIh8QegHNQIQIAR+fCEDIAAgAz4CLCAANQIwIANCIIh8QegHNQIUIAR+fCEDIAAgAz4CMCAANQI0IANCIIh8QegHNQIYIAR+fCEDIAAgAz4CNCAANQI4IANCIIh8QegHNQIcIAR+fCEDIAAgAz4COEHoCCADQiCIPgIcQegIIABBIGogARAOC74fIwF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX5CiceZpA4hBSADQv////8PgyAANQIAIgYgATUCACIHfnwhAyAEIANCIIh8IQQgA0L/////D4MgBX5C/////w+DIQggA0L/////D4NBADUC6AciCSAIfnwhAyAEIANCIIh8IQQgBEIgiCEDIARC/////w+DIAYgATUCBCILfnwhBCADIARCIIh8IQMgBEL/////D4MgADUCBCIKIAd+fCEEIAMgBEIgiHwhAyAEQv////8Pg0EANQLsByINIAh+fCEEIAMgBEIgiHwhAyAEQv////8PgyAFfkL/////D4MhDCAEQv////8PgyAJIAx+fCEEIAMgBEIgiHwhAyADQiCIIQQgA0L/////D4MgBiABNQIIIg9+fCEDIAQgA0IgiHwhBCADQv////8PgyAKIAt+fCEDIAQgA0IgiHwhBCADQv////8PgyAANQIIIg4gB358IQMgBCADQiCIfCEEIANC/////w+DIA0gDH58IQMgBCADQiCIfCEEIANC/////w+DQQA1AvAHIhEgCH58IQMgBCADQiCIfCEEIANC/////w+DIAV+Qv////8PgyEQIANC/////w+DIAkgEH58IQMgBCADQiCIfCEEIARCIIghAyAEQv////8PgyAGIAE1AgwiE358IQQgAyAEQiCIfCEDIARC/////w+DIAogD358IQQgAyAEQiCIfCEDIARC/////w+DIA4gC358IQQgAyAEQiCIfCEDIARC/////w+DIAA1AgwiEiAHfnwhBCADIARCIIh8IQMgBEL/////D4MgDSAQfnwhBCADIARCIIh8IQMgBEL/////D4MgESAMfnwhBCADIARCIIh8IQMgBEL/////D4NBADUC9AciFSAIfnwhBCADIARCIIh8IQMgBEL/////D4MgBX5C/////w+DIRQgBEL/////D4MgCSAUfnwhBCADIARCIIh8IQMgA0IgiCEEIANC/////w+DIAYgATUCECIXfnwhAyAEIANCIIh8IQQgA0L/////D4MgCiATfnwhAyAEIANCIIh8IQQgA0L/////D4MgDiAPfnwhAyAEIANCIIh8IQQgA0L/////D4MgEiALfnwhAyAEIANCIIh8IQQgA0L/////D4MgADUCECIWIAd+fCEDIAQgA0IgiHwhBCADQv////8PgyANIBR+fCEDIAQgA0IgiHwhBCADQv////8PgyARIBB+fCEDIAQgA0IgiHwhBCADQv////8PgyAVIAx+fCEDIAQgA0IgiHwhBCADQv////8Pg0EANQL4ByIZIAh+fCEDIAQgA0IgiHwhBCADQv////8PgyAFfkL/////D4MhGCADQv////8PgyAJIBh+fCEDIAQgA0IgiHwhBCAEQiCIIQMgBEL/////D4MgBiABNQIUIht+fCEEIAMgBEIgiHwhAyAEQv////8PgyAKIBd+fCEEIAMgBEIgiHwhAyAEQv////8PgyAOIBN+fCEEIAMgBEIgiHwhAyAEQv////8PgyASIA9+fCEEIAMgBEIgiHwhAyAEQv////8PgyAWIAt+fCEEIAMgBEIgiHwhAyAEQv////8PgyAANQIUIhogB358IQQgAyAEQiCIfCEDIARC/////w+DIA0gGH58IQQgAyAEQiCIfCEDIARC/////w+DIBEgFH58IQQgAyAEQiCIfCEDIARC/////w+DIBUgEH58IQQgAyAEQiCIfCEDIARC/////w+DIBkgDH58IQQgAyAEQiCIfCEDIARC/////w+DQQA1AvwHIh0gCH58IQQgAyAEQiCIfCEDIARC/////w+DIAV+Qv////8PgyEcIARC/////w+DIAkgHH58IQQgAyAEQiCIfCEDIANCIIghBCADQv////8PgyAGIAE1AhgiH358IQMgBCADQiCIfCEEIANC/////w+DIAogG358IQMgBCADQiCIfCEEIANC/////w+DIA4gF358IQMgBCADQiCIfCEEIANC/////w+DIBIgE358IQMgBCADQiCIfCEEIANC/////w+DIBYgD358IQMgBCADQiCIfCEEIANC/////w+DIBogC358IQMgBCADQiCIfCEEIANC/////w+DIAA1AhgiHiAHfnwhAyAEIANCIIh8IQQgA0L/////D4MgDSAcfnwhAyAEIANCIIh8IQQgA0L/////D4MgESAYfnwhAyAEIANCIIh8IQQgA0L/////D4MgFSAUfnwhAyAEIANCIIh8IQQgA0L/////D4MgGSAQfnwhAyAEIANCIIh8IQQgA0L/////D4MgHSAMfnwhAyAEIANCIIh8IQQgA0L/////D4NBADUCgAgiISAIfnwhAyAEIANCIIh8IQQgA0L/////D4MgBX5C/////w+DISAgA0L/////D4MgCSAgfnwhAyAEIANCIIh8IQQgBEIgiCEDIARC/////w+DIAYgATUCHCIjfnwhBCADIARCIIh8IQMgBEL/////D4MgCiAffnwhBCADIARCIIh8IQMgBEL/////D4MgDiAbfnwhBCADIARCIIh8IQMgBEL/////D4MgEiAXfnwhBCADIARCIIh8IQMgBEL/////D4MgFiATfnwhBCADIARCIIh8IQMgBEL/////D4MgGiAPfnwhBCADIARCIIh8IQMgBEL/////D4MgHiALfnwhBCADIARCIIh8IQMgBEL/////D4MgADUCHCIiIAd+fCEEIAMgBEIgiHwhAyAEQv////8PgyANICB+fCEEIAMgBEIgiHwhAyAEQv////8PgyARIBx+fCEEIAMgBEIgiHwhAyAEQv////8PgyAVIBh+fCEEIAMgBEIgiHwhAyAEQv////8PgyAZIBR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAdIBB+fCEEIAMgBEIgiHwhAyAEQv////8PgyAhIAx+fCEEIAMgBEIgiHwhAyAEQv////8Pg0EANQKECCIlIAh+fCEEIAMgBEIgiHwhAyAEQv////8PgyAFfkL/////D4MhJCAEQv////8PgyAJICR+fCEEIAMgBEIgiHwhAyADQiCIIQQgA0L/////D4MgCiAjfnwhAyAEIANCIIh8IQQgA0L/////D4MgDiAffnwhAyAEIANCIIh8IQQgA0L/////D4MgEiAbfnwhAyAEIANCIIh8IQQgA0L/////D4MgFiAXfnwhAyAEIANCIIh8IQQgA0L/////D4MgGiATfnwhAyAEIANCIIh8IQQgA0L/////D4MgHiAPfnwhAyAEIANCIIh8IQQgA0L/////D4MgIiALfnwhAyAEIANCIIh8IQQgA0L/////D4MgDSAkfnwhAyAEIANCIIh8IQQgA0L/////D4MgESAgfnwhAyAEIANCIIh8IQQgA0L/////D4MgFSAcfnwhAyAEIANCIIh8IQQgA0L/////D4MgGSAYfnwhAyAEIANCIIh8IQQgA0L/////D4MgHSAUfnwhAyAEIANCIIh8IQQgA0L/////D4MgISAQfnwhAyAEIANCIIh8IQQgA0L/////D4MgJSAMfnwhAyAEIANCIIh8IQQgAiADPgIAIARCIIghAyAEQv////8PgyAOICN+fCEEIAMgBEIgiHwhAyAEQv////8PgyASIB9+fCEEIAMgBEIgiHwhAyAEQv////8PgyAWIBt+fCEEIAMgBEIgiHwhAyAEQv////8PgyAaIBd+fCEEIAMgBEIgiHwhAyAEQv////8PgyAeIBN+fCEEIAMgBEIgiHwhAyAEQv////8PgyAiIA9+fCEEIAMgBEIgiHwhAyAEQv////8PgyARICR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAVICB+fCEEIAMgBEIgiHwhAyAEQv////8PgyAZIBx+fCEEIAMgBEIgiHwhAyAEQv////8PgyAdIBh+fCEEIAMgBEIgiHwhAyAEQv////8PgyAhIBR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAlIBB+fCEEIAMgBEIgiHwhAyACIAQ+AgQgA0IgiCEEIANC/////w+DIBIgI358IQMgBCADQiCIfCEEIANC/////w+DIBYgH358IQMgBCADQiCIfCEEIANC/////w+DIBogG358IQMgBCADQiCIfCEEIANC/////w+DIB4gF358IQMgBCADQiCIfCEEIANC/////w+DICIgE358IQMgBCADQiCIfCEEIANC/////w+DIBUgJH58IQMgBCADQiCIfCEEIANC/////w+DIBkgIH58IQMgBCADQiCIfCEEIANC/////w+DIB0gHH58IQMgBCADQiCIfCEEIANC/////w+DICEgGH58IQMgBCADQiCIfCEEIANC/////w+DICUgFH58IQMgBCADQiCIfCEEIAIgAz4CCCAEQiCIIQMgBEL/////D4MgFiAjfnwhBCADIARCIIh8IQMgBEL/////D4MgGiAffnwhBCADIARCIIh8IQMgBEL/////D4MgHiAbfnwhBCADIARCIIh8IQMgBEL/////D4MgIiAXfnwhBCADIARCIIh8IQMgBEL/////D4MgGSAkfnwhBCADIARCIIh8IQMgBEL/////D4MgHSAgfnwhBCADIARCIIh8IQMgBEL/////D4MgISAcfnwhBCADIARCIIh8IQMgBEL/////D4MgJSAYfnwhBCADIARCIIh8IQMgAiAEPgIMIANCIIghBCADQv////8PgyAaICN+fCEDIAQgA0IgiHwhBCADQv////8PgyAeIB9+fCEDIAQgA0IgiHwhBCADQv////8PgyAiIBt+fCEDIAQgA0IgiHwhBCADQv////8PgyAdICR+fCEDIAQgA0IgiHwhBCADQv////8PgyAhICB+fCEDIAQgA0IgiHwhBCADQv////8PgyAlIBx+fCEDIAQgA0IgiHwhBCACIAM+AhAgBEIgiCEDIARC/////w+DIB4gI358IQQgAyAEQiCIfCEDIARC/////w+DICIgH358IQQgAyAEQiCIfCEDIARC/////w+DICEgJH58IQQgAyAEQiCIfCEDIARC/////w+DICUgIH58IQQgAyAEQiCIfCEDIAIgBD4CFCADQiCIIQQgA0L/////D4MgIiAjfnwhAyAEIANCIIh8IQQgA0L/////D4MgJSAkfnwhAyAEIANCIIh8IQQgAiADPgIYIARCIIghAyACIAQ+AhwgA6cEQCACQegHIAIQBxoFIAJB6AcQBQRAIAJB6AcgAhAHGgsLCxIAIAAgAUHoDBAJQegMIAIQEQsLACAAQYgIIAEQEgsVACAAQagNEABByA0QAUGoDSABEBELFwAgACABEBUgAUHoByABEA0gASABEBQLCQBBqAggABAACywAIAAgASACEAYEQCACQegNIAIQBxoFIAJB6A0QBQRAIAJB6A0gAhAHGgsLCxcAIAAgASACEAcEQCACQegNIAIQBhoLCxQAIAAQAkUEQEHoDSAAIAEQBxoLC5wRAwF+AX4BfkL/////DiECQgAhAyAANQIAIAJ+Qv////8PgyEEIAA1AgAgA0IgiHxB6A01AgAgBH58IQMgACADPgIAIAA1AgQgA0IgiHxB6A01AgQgBH58IQMgACADPgIEIAA1AgggA0IgiHxB6A01AgggBH58IQMgACADPgIIIAA1AgwgA0IgiHxB6A01AgwgBH58IQMgACADPgIMIAA1AhAgA0IgiHxB6A01AhAgBH58IQMgACADPgIQIAA1AhQgA0IgiHxB6A01AhQgBH58IQMgACADPgIUIAA1AhggA0IgiHxB6A01AhggBH58IQMgACADPgIYIAA1AhwgA0IgiHxB6A01AhwgBH58IQMgACADPgIcQegOIANCIIg+AgBCACEDIAA1AgQgAn5C/////w+DIQQgADUCBCADQiCIfEHoDTUCACAEfnwhAyAAIAM+AgQgADUCCCADQiCIfEHoDTUCBCAEfnwhAyAAIAM+AgggADUCDCADQiCIfEHoDTUCCCAEfnwhAyAAIAM+AgwgADUCECADQiCIfEHoDTUCDCAEfnwhAyAAIAM+AhAgADUCFCADQiCIfEHoDTUCECAEfnwhAyAAIAM+AhQgADUCGCADQiCIfEHoDTUCFCAEfnwhAyAAIAM+AhggADUCHCADQiCIfEHoDTUCGCAEfnwhAyAAIAM+AhwgADUCICADQiCIfEHoDTUCHCAEfnwhAyAAIAM+AiBB6A4gA0IgiD4CBEIAIQMgADUCCCACfkL/////D4MhBCAANQIIIANCIIh8QegNNQIAIAR+fCEDIAAgAz4CCCAANQIMIANCIIh8QegNNQIEIAR+fCEDIAAgAz4CDCAANQIQIANCIIh8QegNNQIIIAR+fCEDIAAgAz4CECAANQIUIANCIIh8QegNNQIMIAR+fCEDIAAgAz4CFCAANQIYIANCIIh8QegNNQIQIAR+fCEDIAAgAz4CGCAANQIcIANCIIh8QegNNQIUIAR+fCEDIAAgAz4CHCAANQIgIANCIIh8QegNNQIYIAR+fCEDIAAgAz4CICAANQIkIANCIIh8QegNNQIcIAR+fCEDIAAgAz4CJEHoDiADQiCIPgIIQgAhAyAANQIMIAJ+Qv////8PgyEEIAA1AgwgA0IgiHxB6A01AgAgBH58IQMgACADPgIMIAA1AhAgA0IgiHxB6A01AgQgBH58IQMgACADPgIQIAA1AhQgA0IgiHxB6A01AgggBH58IQMgACADPgIUIAA1AhggA0IgiHxB6A01AgwgBH58IQMgACADPgIYIAA1AhwgA0IgiHxB6A01AhAgBH58IQMgACADPgIcIAA1AiAgA0IgiHxB6A01AhQgBH58IQMgACADPgIgIAA1AiQgA0IgiHxB6A01AhggBH58IQMgACADPgIkIAA1AiggA0IgiHxB6A01AhwgBH58IQMgACADPgIoQegOIANCIIg+AgxCACEDIAA1AhAgAn5C/////w+DIQQgADUCECADQiCIfEHoDTUCACAEfnwhAyAAIAM+AhAgADUCFCADQiCIfEHoDTUCBCAEfnwhAyAAIAM+AhQgADUCGCADQiCIfEHoDTUCCCAEfnwhAyAAIAM+AhggADUCHCADQiCIfEHoDTUCDCAEfnwhAyAAIAM+AhwgADUCICADQiCIfEHoDTUCECAEfnwhAyAAIAM+AiAgADUCJCADQiCIfEHoDTUCFCAEfnwhAyAAIAM+AiQgADUCKCADQiCIfEHoDTUCGCAEfnwhAyAAIAM+AiggADUCLCADQiCIfEHoDTUCHCAEfnwhAyAAIAM+AixB6A4gA0IgiD4CEEIAIQMgADUCFCACfkL/////D4MhBCAANQIUIANCIIh8QegNNQIAIAR+fCEDIAAgAz4CFCAANQIYIANCIIh8QegNNQIEIAR+fCEDIAAgAz4CGCAANQIcIANCIIh8QegNNQIIIAR+fCEDIAAgAz4CHCAANQIgIANCIIh8QegNNQIMIAR+fCEDIAAgAz4CICAANQIkIANCIIh8QegNNQIQIAR+fCEDIAAgAz4CJCAANQIoIANCIIh8QegNNQIUIAR+fCEDIAAgAz4CKCAANQIsIANCIIh8QegNNQIYIAR+fCEDIAAgAz4CLCAANQIwIANCIIh8QegNNQIcIAR+fCEDIAAgAz4CMEHoDiADQiCIPgIUQgAhAyAANQIYIAJ+Qv////8PgyEEIAA1AhggA0IgiHxB6A01AgAgBH58IQMgACADPgIYIAA1AhwgA0IgiHxB6A01AgQgBH58IQMgACADPgIcIAA1AiAgA0IgiHxB6A01AgggBH58IQMgACADPgIgIAA1AiQgA0IgiHxB6A01AgwgBH58IQMgACADPgIkIAA1AiggA0IgiHxB6A01AhAgBH58IQMgACADPgIoIAA1AiwgA0IgiHxB6A01AhQgBH58IQMgACADPgIsIAA1AjAgA0IgiHxB6A01AhggBH58IQMgACADPgIwIAA1AjQgA0IgiHxB6A01AhwgBH58IQMgACADPgI0QegOIANCIIg+AhhCACEDIAA1AhwgAn5C/////w+DIQQgADUCHCADQiCIfEHoDTUCACAEfnwhAyAAIAM+AhwgADUCICADQiCIfEHoDTUCBCAEfnwhAyAAIAM+AiAgADUCJCADQiCIfEHoDTUCCCAEfnwhAyAAIAM+AiQgADUCKCADQiCIfEHoDTUCDCAEfnwhAyAAIAM+AiggADUCLCADQiCIfEHoDTUCECAEfnwhAyAAIAM+AiwgADUCMCADQiCIfEHoDTUCFCAEfnwhAyAAIAM+AjAgADUCNCADQiCIfEHoDTUCGCAEfnwhAyAAIAM+AjQgADUCOCADQiCIfEHoDTUCHCAEfnwhAyAAIAM+AjhB6A4gA0IgiD4CHEHoDiAAQSBqIAEQGAu+HyMBfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+AX4BfgF+Qv////8OIQUgA0L/////D4MgADUCACIGIAE1AgAiB358IQMgBCADQiCIfCEEIANC/////w+DIAV+Qv////8PgyEIIANC/////w+DQQA1AugNIgkgCH58IQMgBCADQiCIfCEEIARCIIghAyAEQv////8PgyAGIAE1AgQiC358IQQgAyAEQiCIfCEDIARC/////w+DIAA1AgQiCiAHfnwhBCADIARCIIh8IQMgBEL/////D4NBADUC7A0iDSAIfnwhBCADIARCIIh8IQMgBEL/////D4MgBX5C/////w+DIQwgBEL/////D4MgCSAMfnwhBCADIARCIIh8IQMgA0IgiCEEIANC/////w+DIAYgATUCCCIPfnwhAyAEIANCIIh8IQQgA0L/////D4MgCiALfnwhAyAEIANCIIh8IQQgA0L/////D4MgADUCCCIOIAd+fCEDIAQgA0IgiHwhBCADQv////8PgyANIAx+fCEDIAQgA0IgiHwhBCADQv////8Pg0EANQLwDSIRIAh+fCEDIAQgA0IgiHwhBCADQv////8PgyAFfkL/////D4MhECADQv////8PgyAJIBB+fCEDIAQgA0IgiHwhBCAEQiCIIQMgBEL/////D4MgBiABNQIMIhN+fCEEIAMgBEIgiHwhAyAEQv////8PgyAKIA9+fCEEIAMgBEIgiHwhAyAEQv////8PgyAOIAt+fCEEIAMgBEIgiHwhAyAEQv////8PgyAANQIMIhIgB358IQQgAyAEQiCIfCEDIARC/////w+DIA0gEH58IQQgAyAEQiCIfCEDIARC/////w+DIBEgDH58IQQgAyAEQiCIfCEDIARC/////w+DQQA1AvQNIhUgCH58IQQgAyAEQiCIfCEDIARC/////w+DIAV+Qv////8PgyEUIARC/////w+DIAkgFH58IQQgAyAEQiCIfCEDIANCIIghBCADQv////8PgyAGIAE1AhAiF358IQMgBCADQiCIfCEEIANC/////w+DIAogE358IQMgBCADQiCIfCEEIANC/////w+DIA4gD358IQMgBCADQiCIfCEEIANC/////w+DIBIgC358IQMgBCADQiCIfCEEIANC/////w+DIAA1AhAiFiAHfnwhAyAEIANCIIh8IQQgA0L/////D4MgDSAUfnwhAyAEIANCIIh8IQQgA0L/////D4MgESAQfnwhAyAEIANCIIh8IQQgA0L/////D4MgFSAMfnwhAyAEIANCIIh8IQQgA0L/////D4NBADUC+A0iGSAIfnwhAyAEIANCIIh8IQQgA0L/////D4MgBX5C/////w+DIRggA0L/////D4MgCSAYfnwhAyAEIANCIIh8IQQgBEIgiCEDIARC/////w+DIAYgATUCFCIbfnwhBCADIARCIIh8IQMgBEL/////D4MgCiAXfnwhBCADIARCIIh8IQMgBEL/////D4MgDiATfnwhBCADIARCIIh8IQMgBEL/////D4MgEiAPfnwhBCADIARCIIh8IQMgBEL/////D4MgFiALfnwhBCADIARCIIh8IQMgBEL/////D4MgADUCFCIaIAd+fCEEIAMgBEIgiHwhAyAEQv////8PgyANIBh+fCEEIAMgBEIgiHwhAyAEQv////8PgyARIBR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAVIBB+fCEEIAMgBEIgiHwhAyAEQv////8PgyAZIAx+fCEEIAMgBEIgiHwhAyAEQv////8Pg0EANQL8DSIdIAh+fCEEIAMgBEIgiHwhAyAEQv////8PgyAFfkL/////D4MhHCAEQv////8PgyAJIBx+fCEEIAMgBEIgiHwhAyADQiCIIQQgA0L/////D4MgBiABNQIYIh9+fCEDIAQgA0IgiHwhBCADQv////8PgyAKIBt+fCEDIAQgA0IgiHwhBCADQv////8PgyAOIBd+fCEDIAQgA0IgiHwhBCADQv////8PgyASIBN+fCEDIAQgA0IgiHwhBCADQv////8PgyAWIA9+fCEDIAQgA0IgiHwhBCADQv////8PgyAaIAt+fCEDIAQgA0IgiHwhBCADQv////8PgyAANQIYIh4gB358IQMgBCADQiCIfCEEIANC/////w+DIA0gHH58IQMgBCADQiCIfCEEIANC/////w+DIBEgGH58IQMgBCADQiCIfCEEIANC/////w+DIBUgFH58IQMgBCADQiCIfCEEIANC/////w+DIBkgEH58IQMgBCADQiCIfCEEIANC/////w+DIB0gDH58IQMgBCADQiCIfCEEIANC/////w+DQQA1AoAOIiEgCH58IQMgBCADQiCIfCEEIANC/////w+DIAV+Qv////8PgyEgIANC/////w+DIAkgIH58IQMgBCADQiCIfCEEIARCIIghAyAEQv////8PgyAGIAE1AhwiI358IQQgAyAEQiCIfCEDIARC/////w+DIAogH358IQQgAyAEQiCIfCEDIARC/////w+DIA4gG358IQQgAyAEQiCIfCEDIARC/////w+DIBIgF358IQQgAyAEQiCIfCEDIARC/////w+DIBYgE358IQQgAyAEQiCIfCEDIARC/////w+DIBogD358IQQgAyAEQiCIfCEDIARC/////w+DIB4gC358IQQgAyAEQiCIfCEDIARC/////w+DIAA1AhwiIiAHfnwhBCADIARCIIh8IQMgBEL/////D4MgDSAgfnwhBCADIARCIIh8IQMgBEL/////D4MgESAcfnwhBCADIARCIIh8IQMgBEL/////D4MgFSAYfnwhBCADIARCIIh8IQMgBEL/////D4MgGSAUfnwhBCADIARCIIh8IQMgBEL/////D4MgHSAQfnwhBCADIARCIIh8IQMgBEL/////D4MgISAMfnwhBCADIARCIIh8IQMgBEL/////D4NBADUChA4iJSAIfnwhBCADIARCIIh8IQMgBEL/////D4MgBX5C/////w+DISQgBEL/////D4MgCSAkfnwhBCADIARCIIh8IQMgA0IgiCEEIANC/////w+DIAogI358IQMgBCADQiCIfCEEIANC/////w+DIA4gH358IQMgBCADQiCIfCEEIANC/////w+DIBIgG358IQMgBCADQiCIfCEEIANC/////w+DIBYgF358IQMgBCADQiCIfCEEIANC/////w+DIBogE358IQMgBCADQiCIfCEEIANC/////w+DIB4gD358IQMgBCADQiCIfCEEIANC/////w+DICIgC358IQMgBCADQiCIfCEEIANC/////w+DIA0gJH58IQMgBCADQiCIfCEEIANC/////w+DIBEgIH58IQMgBCADQiCIfCEEIANC/////w+DIBUgHH58IQMgBCADQiCIfCEEIANC/////w+DIBkgGH58IQMgBCADQiCIfCEEIANC/////w+DIB0gFH58IQMgBCADQiCIfCEEIANC/////w+DICEgEH58IQMgBCADQiCIfCEEIANC/////w+DICUgDH58IQMgBCADQiCIfCEEIAIgAz4CACAEQiCIIQMgBEL/////D4MgDiAjfnwhBCADIARCIIh8IQMgBEL/////D4MgEiAffnwhBCADIARCIIh8IQMgBEL/////D4MgFiAbfnwhBCADIARCIIh8IQMgBEL/////D4MgGiAXfnwhBCADIARCIIh8IQMgBEL/////D4MgHiATfnwhBCADIARCIIh8IQMgBEL/////D4MgIiAPfnwhBCADIARCIIh8IQMgBEL/////D4MgESAkfnwhBCADIARCIIh8IQMgBEL/////D4MgFSAgfnwhBCADIARCIIh8IQMgBEL/////D4MgGSAcfnwhBCADIARCIIh8IQMgBEL/////D4MgHSAYfnwhBCADIARCIIh8IQMgBEL/////D4MgISAUfnwhBCADIARCIIh8IQMgBEL/////D4MgJSAQfnwhBCADIARCIIh8IQMgAiAEPgIEIANCIIghBCADQv////8PgyASICN+fCEDIAQgA0IgiHwhBCADQv////8PgyAWIB9+fCEDIAQgA0IgiHwhBCADQv////8PgyAaIBt+fCEDIAQgA0IgiHwhBCADQv////8PgyAeIBd+fCEDIAQgA0IgiHwhBCADQv////8PgyAiIBN+fCEDIAQgA0IgiHwhBCADQv////8PgyAVICR+fCEDIAQgA0IgiHwhBCADQv////8PgyAZICB+fCEDIAQgA0IgiHwhBCADQv////8PgyAdIBx+fCEDIAQgA0IgiHwhBCADQv////8PgyAhIBh+fCEDIAQgA0IgiHwhBCADQv////8PgyAlIBR+fCEDIAQgA0IgiHwhBCACIAM+AgggBEIgiCEDIARC/////w+DIBYgI358IQQgAyAEQiCIfCEDIARC/////w+DIBogH358IQQgAyAEQiCIfCEDIARC/////w+DIB4gG358IQQgAyAEQiCIfCEDIARC/////w+DICIgF358IQQgAyAEQiCIfCEDIARC/////w+DIBkgJH58IQQgAyAEQiCIfCEDIARC/////w+DIB0gIH58IQQgAyAEQiCIfCEDIARC/////w+DICEgHH58IQQgAyAEQiCIfCEDIARC/////w+DICUgGH58IQQgAyAEQiCIfCEDIAIgBD4CDCADQiCIIQQgA0L/////D4MgGiAjfnwhAyAEIANCIIh8IQQgA0L/////D4MgHiAffnwhAyAEIANCIIh8IQQgA0L/////D4MgIiAbfnwhAyAEIANCIIh8IQQgA0L/////D4MgHSAkfnwhAyAEIANCIIh8IQQgA0L/////D4MgISAgfnwhAyAEIANCIIh8IQQgA0L/////D4MgJSAcfnwhAyAEIANCIIh8IQQgAiADPgIQIARCIIghAyAEQv////8PgyAeICN+fCEEIAMgBEIgiHwhAyAEQv////8PgyAiIB9+fCEEIAMgBEIgiHwhAyAEQv////8PgyAhICR+fCEEIAMgBEIgiHwhAyAEQv////8PgyAlICB+fCEEIAMgBEIgiHwhAyACIAQ+AhQgA0IgiCEEIANC/////w+DICIgI358IQMgBCADQiCIfCEEIANC/////w+DICUgJH58IQMgBCADQiCIfCEEIAIgAz4CGCAEQiCIIQMgAiAEPgIcIAOnBEAgAkHoDSACEAcaBSACQegNEAUEQCACQegNIAIQBxoLCwsSACAAIAFB6BIQCUHoEiACEBsLCwAgAEGIDiABEBwLFQAgAEGoExAAQcgTEAFBqBMgARAbCxcAIAAgARAfIAFB6A0gARANIAEgARAeCwkAQagOIAAQAAsVACAAIAFB6BMQHEHoE0GIDiACEBwLCwAgAEHoDSABEA0LCgAgAEHAAGoQAgsVACAAEAEgAEEgahAXIABBwABqEAELIgAgACABEAAgAEEgaiABQSBqEAAgAEHAAGogAUHAAGoQAAuGAgAgABAkBEAgACABECYPCyAAIABBiBQQEiAAQSBqIABBIGpBqBQQEkGoFEGoFEHIFBASIABBqBRB6BQQDkHoFEHoFEHoFBASQegUQYgUQegUEA9B6BRByBRB6BQQD0HoFEHoFEHoFBAOQYgUQYgUQYgVEA5BiBVBiBRBiBUQDkGIFUGIFUGoFRASIABBIGogAEHAAGpByBUQEkHoFEHoFCABEA5BqBUgASABEA9ByBRByBRB6BUQDkHoFUHoFUHoFRAOQegVQegVQegVEA5B6BQgASABQSBqEA8gAUEgakGIFSABQSBqEBIgAUEgakHoFSABQSBqEA9ByBVByBUgAUHAAGoQDgusAwIBfwF/IABBwABqIQMgAUHAAGohBCAAECQEQCABIAIQJg8LIAEQJARAIAAgAhAmDwsgAyADQYgWEBIgBCAEQagWEBIgAEGoFkHIFhASIAFBiBZB6BYQEiADQYgWQYgXEBIgBEGoFkGoFxASIABBIGpBqBdByBcQEiABQSBqQYgXQegXEBJByBZB6BYQBARAQcgXQegXEAQEQCAAIAIQJw8LC0HoFkHIFkGIGBAPQegXQcgXQagYEA9BiBhBiBhByBgQDkHIGEHIGEHIGBASQYgYQcgYQegYEBJBqBhBqBhBiBkQDkHIFkHIGEHIGRASQYgZQYgZQagZEBJByBlByBlB6BkQDkGoGUHoGCACEA8gAkHoGSACEA9ByBdB6BhBiBoQEkGIGkGIGkGIGhAOQcgZIAIgAkEgahAPIAJBIGpBiBkgAkEgahASIAJBIGpBiBogAkEgahAPIAMgBCACQcAAahAOIAJBwABqIAJBwABqIAJBwABqEBIgAkHAAGpBiBYgAkHAAGoQDyACQcAAakGoFiACQcAAahAPIAJBwABqQYgYIAJBwABqEBILIgAgACABEAAgAEEgaiABQSBqEBAgAEHAAGogAUHAAGoQAAsQACABIAIQKSAAIAIgAhAoCyIAIAAgARAVIABBIGogAUEgahAVIABBwABqIAFBwABqEBULIgAgACABEBQgAEEgaiABQSBqEBQgAEHAAGogAUHAAGoQFAtPACAAECQEQCABECUFIABBwABqQagaEBZBqBpBqBpByBoQEkGoGkHIGkHoGhASIABByBogARASIABBIGpB6BogAUEgahASIAFBwABqEBcLC6cCAgF/AX8gAEGIGxAmIAMQJSACIQQCQANAIARBAWshBCABIARqLQAAIQUgAyADECcgBUGAAU8EQCAFQYABayEFQYgbIAMgAxAoCyADIAMQJyAFQcAATwRAIAVBwABrIQVBiBsgAyADECgLIAMgAxAnIAVBIE8EQCAFQSBrIQVBiBsgAyADECgLIAMgAxAnIAVBEE8EQCAFQRBrIQVBiBsgAyADECgLIAMgAxAnIAVBCE8EQCAFQQhrIQVBiBsgAyADECgLIAMgAxAnIAVBBE8EQCAFQQRrIQVBiBsgAyADECgLIAMgAxAnIAVBAk8EQCAFQQJrIQVBiBsgAyADECgLIAMgAxAnIAVBAU8EQCAFQQFrIQVBiBsgAyADECgLIARFDQEMAAsLCysCAX8BfyAAQQV2QQJ0IQFBASAAQR9xdCECIAEgASgC6NsBIAJyNgLo2wELJAIBfwF/IABBBXZBAnQhAUEBIABBH3F0IQIgASgC6NsBIAJxC6ABBAF/AX8BfwF/IAAhAkHoGxAlQQAhBAJAA0AgBCABRg0BQegbQQEgBHRB4ABsaiEDIAIQAiEFIAIgAxAAIAJBIGohAiADQSBqIQMgAiADEAAgAkEgaiECIANBIGohAyAFBEAgAxABBSADEBcLIARBAWohBAwACwtB6NsBQpeChIAQNwMAQfDbAUIBNwMAQfjbAUIBNwMAQYDcAUIANwMAC0ADAX8BfwF/QegbIABB4ABsaiEBIAAQMEUEQCAALQCI3AEQMiECIAAtAIjeARAyIQMgAiADIAEQKCAAEC8LIAELpQEEAX8BfwF+AX5BACEDAkADQCADQSBGDQFCACEGQQAhBAJAA0AgBCABRg0BIAAgBEEgbCADamoxAAAhBSAFIAVCHIaEQo+AgIDwAYMhBSAFIAVCDoaEQoOAjICwgMABgyEFIAUgBUIHhoRCgYKEiJCgwIABgyEFIAYgBSAErYaEIQYgBEEBaiEEDAALCyACIANBCGxqIAY3AwAgA0EBaiEDDAALCwtLAQF/IAAgAkGI4AEQMyADECUgASACEDFBACEEAkADQCAEQYACRg0BIAMgAxAnIANBh+IBIARrLQAAEDIgAxAoIARBAWohBAwACwsLfgQBfwF/AX8BfyAAIQUgASEGIAUgAiADbiADbEEgbGohCAJAA0AgBSAIRg0BIAUgBiADQYjiARA0QYjiASAEIAQQKCAFQSAgA2xqIQUgBkHAACADbGohBgwACwsgAiADcCEHIAcEQCAFIAYgB0GI4gEQNEGI4gEgBCAEECgLC04CAX8BfyAAIAJB6OIBEDMgASACEDFBACEEAkADQCAEQYACRg0BIAMgBEHgAGxqIQUgBUHn5AEgBGstAAAQMiAFECggBEEBaiEEDAALCwspAQF/QQAhAgJAA0AgAiABRg0BIAAgAkHgAGxqECUgAkEBaiECDAALCwtIAgF/AX8gACEEIAQgAhAmIARB4ABqIQRBASEDAkADQCADIAFGDQEgAiACECcgBCACIAIQKCAEQeAAaiEEIANBAWohAwwACwsLigEEAX8BfwF/AX9B6OQBQYACEDcgACEFIAEhBiAFIAIgA24gA2xBIGxqIQgCQANAIAUgCEYNASAFIAYgA0Ho5AEQNiAFQSAgA2xqIQUgBkHAACADbGohBgwACwsgAiADcCEHIAcEQCAFIAYgB0Ho5AEQNgtB6OQBQYACQeikAxA4QeikAyAEIAQQKAtGACAAQf8BcS0AiLQDQRh0IABBCHZB/wFxLQCItANBEHRqIABBEHZB/wFxLQCItANBCHQgAEEYdkH/AXEtAIi0A2pqIAF3C2cFAX8BfwF/AX8Bf0EBIAF0IQJBACEDAkADQCADIAJGDQEgACADQSBsaiEFIAMgARA6IQQgACAEQSBsaiEGIAMgBEkEQCAFQYi2AxAAIAYgBRAAQYi2AyAGEAALIANBAWohAwwACwsL7wEJAX8BfwF/AX8BfwF/AX8BfwF/IAAgARA7QQEgAXQhCEEBIQMCQANAIAMgAUsNAUEBIAN0IQZByKUDIANBIGxqIQlBACEEAkADQCAEIAhPDQEgAgRAIAlBIGpBqLYDEAAFQai2AxAhCyAGQQF2IQdBACEFAkADQCAFIAdPDQEgACAEIAVqQSBsaiEKIAogB0EgbGohC0GotgMgC0HItgMQHCAKQei2AxAAQei2A0HItgMgChAYQei2A0HItgMgCxAZQai2AyAJQai2AxAcIAVBAWohBQwACwsgBCAGaiEEDAALCyADQQFqIQMMAAsLCz4DAX8BfwF/IAAhAyABIQQgACACQSBsaiEFAkADQCADIAVGDQEgAyAEEAAgA0EgaiEDIARBwABqIQQMAAsLCz0DAX8BfwF/IAAhAyABIQQgACACQSBsaiEFAkADQCADIAVGDQEgAyAEEB8gA0EgaiEDIARBIGohBAwACwsLPQMBfwF/AX8gACEDIAEhBCAAIAJBIGxqIQUCQANAIAMgBUYNASADIAQQHiADQSBqIQMgBEEgaiEEDAALCwuWAQcBfwF/AX8BfwF/AX8Bf0EBIAF0IQJB6KwDIAFBIGxqIQQgAkEBayEGQQEhBSACQQF2IQMCQANAIAUgA0YNASAAIAVBIGxqIQcgACACIAVrQSBsaiEIIAdBiLcDEAAgCCAEIAcQHEGItwMgBCAIEBwgBUEBaiEFDAALCyAAIAQgABAcIAAgA0EgbGohCCAIIAQgCBAcC0MCAX8BfyAAQQF2IQJBACEBAkADQCACRQ0BIAJBAXYhAiABQQFqIQEMAAsLIABBASABdEcEQAALIAFBHEsEQAALIAELEgEBfyABEEEhAyAAIAMgAhA8CxgBAX8gARBBIQMgACADIAIQPCAAIAMQQAtMBAF/AX8BfwF/IAAhBCABIQUgAyEGIAAgAkEgbGohBwJAA0AgBCAHRg0BIAQgBSAGEBwgBEEgaiEEIAVBIGohBSAGQSBqIQYMAAsLCy4CAX8BfyAAIQMgACABQSBsaiECAkADQCADIAJGDQEgAxABIANBIGohAwwACwsLjgEGAX8BfwF/AX8BfwF/QQAhBCAAIQYgASEHAkADQCAEIAJGDQEgBigCACEJIAZBBGohBkEAIQUCQANAIAUgCUYNASADIAYoAgBBIGxqIQggBkEEaiEGIAcgBkGotwMQHEGotwMgCCAIEBggBkEgaiEGIAVBAWohBQwACwsgB0EgaiEHIARBAWohBAwACwsLDgAgABACIABBIGoQAnELDQAgABABIABBIGoQAQsNACAAEBcgAEEgahABCxQAIAAgARAAIABBIGogAUEgahAAC3kAIAAgAUHotwMQEiAAQSBqIAFBIGpBiLgDEBIgACAAQSBqQai4AxAOIAEgAUEgakHIuAMQDkGouANByLgDQai4AxASQYi4A0HItwMgAhASQei3AyACIAIQDkHotwNBiLgDIAJBIGoQDkGouAMgAkEgaiACQSBqEA8LGwAgACABIAIQDiAAQSBqIAFBIGogAkEgahAOCxsAIAAgASACEA8gAEEgaiABQSBqIAJBIGoQDwsUACAAIAEQECAAQSBqIAFBIGoQEAsUACAAIAEQFCAAQSBqIAFBIGoQFAsUACAAIAEQFSAAQSBqIAFBIGoQFQsVACAAIAEQBCAAQSBqIAFBIGoQBHELaAAgACAAQei4AxASIABBIGogAEEgakGIuQMQEkGIuQNByLcDQai5AxASQei4A0GouQNBqLkDEA9BqLkDQci5AxAWIABByLkDIAEQEiAAQSBqQci5AyABQSBqEBIgAUEgaiABQSBqEBALCgAgAEGAAWoQRwsWACAAEEggAEHAAGoQSSAAQYABahBICyQAIAAgARBKIABBwABqIAFBwABqEEogAEGAAWogAUGAAWoQSgu8AgAgABBTBEAgACABEFUPCyAAIABB6LkDEEsgAEHAAGogAEHAAGpBqLoDEEtBqLoDQai6A0HougMQSyAAQai6A0GouwMQTEGouwNBqLsDQai7AxBLQai7A0HouQNBqLsDEE1BqLsDQei6A0GouwMQTUGouwNBqLsDQai7AxBMQei5A0HouQNB6LsDEExB6LsDQei5A0HouwMQTEHouwNB6LsDQai8AxBLIABBwABqIABBgAFqQei8AxBLQai7A0GouwMgARBMQai8AyABIAEQTUHougNB6LoDQai9AxBMQai9A0GovQNBqL0DEExBqL0DQai9A0GovQMQTEGouwMgASABQcAAahBNIAFBwABqQei7AyABQcAAahBLIAFBwABqQai9AyABQcAAahBNQei8A0HovAMgAUGAAWoQTAvvAwIBfwF/IABBgAFqIQMgAUGAAWohBCAAEFMEQCABIAIQVQ8LIAEQUwRAIAAgAhBVDwsgAyADQei9AxBLIAQgBEGovgMQSyAAQai+A0HovgMQSyABQei9A0GovwMQSyADQei9A0HovwMQSyAEQai+A0GowAMQSyAAQcAAakGowANB6MADEEsgAUHAAGpB6L8DQajBAxBLQei+A0GovwMQUQRAQejAA0GowQMQUQRAIAAgAhBWDwsLQai/A0HovgNB6MEDEE1BqMEDQejAA0GowgMQTUHowQNB6MEDQejCAxBMQejCA0HowgNB6MIDEEtB6MEDQejCA0GowwMQS0GowgNBqMIDQejDAxBMQei+A0HowgNB6MQDEEtB6MMDQejDA0GoxAMQS0HoxANB6MQDQajFAxBMQajEA0GowwMgAhBNIAJBqMUDIAIQTUHowANBqMMDQejFAxBLQejFA0HoxQNB6MUDEExB6MQDIAIgAkHAAGoQTSACQcAAakHowwMgAkHAAGoQSyACQcAAakHoxQMgAkHAAGoQTSADIAQgAkGAAWoQTCACQYABaiACQYABaiACQYABahBLIAJBgAFqQei9AyACQYABahBNIAJBgAFqQai+AyACQYABahBNIAJBgAFqQejBAyACQYABahBLCyQAIAAgARBKIABBwABqIAFBwABqEE4gAEGAAWogAUGAAWoQSgsQACABIAIQWCAAIAIgAhBXCyQAIAAgARBQIABBwABqIAFBwABqEFAgAEGAAWogAUGAAWoQUAskACAAIAEQTyAAQcAAaiABQcAAahBPIABBgAFqIAFBgAFqEE8LWgAgABBTBEAgARBUBSAAQYABakGoxgMQUkGoxgNBqMYDQejGAxBLQajGA0HoxgNBqMcDEEsgAEHoxgMgARBLIABBwABqQajHAyABQcAAahBLIAFBgAFqEEkLC7ACAgF/AX8gAEHoxwMQVSADEFQgAiEEAkADQCAEQQFrIQQgASAEai0AACEFIAMgAxBWIAVBgAFPBEAgBUGAAWshBUHoxwMgAyADEFcLIAMgAxBWIAVBwABPBEAgBUHAAGshBUHoxwMgAyADEFcLIAMgAxBWIAVBIE8EQCAFQSBrIQVB6McDIAMgAxBXCyADIAMQViAFQRBPBEAgBUEQayEFQejHAyADIAMQVwsgAyADEFYgBUEITwRAIAVBCGshBUHoxwMgAyADEFcLIAMgAxBWIAVBBE8EQCAFQQRrIQVB6McDIAMgAxBXCyADIAMQViAFQQJPBEAgBUECayEFQejHAyADIAMQVwsgAyADEFYgBUEBTwRAIAVBAWshBUHoxwMgAyADEFcLIARFDQEMAAsLCysCAX8BfyAAQQV2QQJ0IQFBASAAQR9xdCECIAEgASgCqMkGIAJyNgKoyQYLJAIBfwF/IABBBXZBAnQhAUEBIABBH3F0IQIgASgCqMkGIAJxC6YBBAF/AX8BfwF/IAAhAkGoyQMQVEEAIQQCQANAIAQgAUYNAUGoyQNBASAEdEHAAWxqIQMgAhBHIQUgAiADEEogAkHAAGohAiADQcAAaiEDIAIgAxBKIAJBwABqIQIgA0HAAGohAyAFBEAgAxBIBSADEEkLIARBAWohBAwACwtBqMkGQpeChIAQNwMAQbDJBkIBNwMAQbjJBkIBNwMAQcDJBkIANwMAC0EDAX8BfwF/QajJAyAAQcABbGohASAAEF9FBEAgAC0AyMkGEGEhAiAALQDIywYQYSEDIAIgAyABEFcgABBeCyABC6UBBAF/AX8BfgF+QQAhAwJAA0AgA0EgRg0BQgAhBkEAIQQCQANAIAQgAUYNASAAIARBIGwgA2pqMQAAIQUgBSAFQhyGhEKPgICA8AGDIQUgBSAFQg6GhEKDgIyAsIDAAYMhBSAFIAVCB4aEQoGChIiQoMCAAYMhBSAGIAUgBK2GhCEGIARBAWohBAwACwsgAiADQQhsaiAGNwMAIANBAWohAwwACwsLSwEBfyAAIAJByM0GEGIgAxBUIAEgAhBgQQAhBAJAA0AgBEGAAkYNASADIAMQViADQcfPBiAEay0AABBhIAMQVyAEQQFqIQQMAAsLC34EAX8BfwF/AX8gACEFIAEhBiAFIAIgA24gA2xBIGxqIQgCQANAIAUgCEYNASAFIAYgA0HIzwYQY0HIzwYgBCAEEFcgBUEgIANsaiEFIAZBgAEgA2xqIQYMAAsLIAIgA3AhByAHBEAgBSAGIAdByM8GEGNByM8GIAQgBBBXCwtOAgF/AX8gACACQYjRBhBiIAEgAhBgQQAhBAJAA0AgBEGAAkYNASADIARBwAFsaiEFIAVBh9MGIARrLQAAEGEgBRBXIARBAWohBAwACwsLKQEBf0EAIQICQANAIAIgAUYNASAAIAJBwAFsahBUIAJBAWohAgwACwsLSAIBfwF/IAAhBCAEIAIQVSAEQcABaiEEQQEhAwJAA0AgAyABRg0BIAIgAhBWIAQgAiACEFcgBEHAAWohBCADQQFqIQMMAAsLC4oBBAF/AX8BfwF/QYjTBkGAAhBmIAAhBSABIQYgBSACIANuIANsQSBsaiEIAkADQCAFIAhGDQEgBSAGIANBiNMGEGUgBUEgIANsaiEFIAZBgAEgA2xqIQYMAAsLIAIgA3AhByAHBEAgBSAGIAdBiNMGEGULQYjTBkGAAkGI0wkQZ0GI0wkgBCAEEFcLJAEBfyADIQQCQANAIAAgASACEBIgBEEBayEEIARFDQEMAAsLCyQBAX8gAyEEAkADQCAAIAEgAhATIARBAWshBCAERQ0BDAALCwsL/hsSAEEACwRIagIAAEEICyABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABB6AcLIEf9fNgWjCA8jcpxaJFqgZddWIGBtkVQuCmgMeFyTmQwAEGICAsgifqKU1v8LPP7AUXUERnntfZ/QQr/HqtHHzW4ynGf2AYAQagICyCdDY/FjUNd0z0Lx/Uo63gKLEZ5eG+jbmYv3weawXcKDgBByAgLIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEHoDQsgAQAA8JP14UORcLl5SOgzKF1YgYG2RVC4KaAx4XJOZDAAQYgOCyCnbSGuRea4G+NZXOOxOv5ThYC7Uz2DSYylRE5/sdAWAgBBqA4LIPv//08cNJasKc1gn5V2/DYuRnl4b6NuZi/fB5rBdwoOAEHIDgsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQYjcAQuAAgAAAAIABAQGAAgICggMDAwAEBASEBQUFBAYGBgYGBgcACAgIiAkJCQgKCgoKCgoLCAwMDAwMDA0MDAwODA4ODgAQEBCQEREREBISEhISEhMQFBQUFBQUFRQUFBYUFhYWEBgYGBgYGBkYGBgaGBoaGhgYGBwYHBwcGBwcHBwcHB4AICAgoCEhISAiIiIiIiIjICQkJCQkJCUkJCQmJCYmJiAoKCgoKCgpKCgoKigqKiooKCgsKCwsLCgsLCwsLCwuIDAwMDAwMDEwMDAyMDIyMjAwMDQwNDQ0MDQ0NDQ0NDYwMDA4MDg4ODA4ODg4ODg6MDg4ODg4ODw4ODg8ODw8PAAQYjeAQuAAgAAAAEAAQIBAAECAQQBAgMAAQIBBAECAwgBAgMEBQYDAAECAQQBAgMIAQIDBAUGAxABAgMEBQYDCAkKAwwFBgcAAQIBBAECAwgBAgMEBQYDEAECAwQFBgMICQoDDAUGByABAgMEBQYDCAkKAwwFBgcQERIDFAUGBxgJCgsMDQ4HAAECAQQBAgMIAQIDBAUGAxABAgMEBQYDCAkKAwwFBgcgAQIDBAUGAwgJCgMMBQYHEBESAxQFBgcYCQoLDA0OB0ABAgMEBQYDCAkKAwwFBgcQERIDFAUGBxgJCgsMDQ4HICEiAyQFBgcoCQoLDA0OBzAREhMUFRYHGBkaCxwNDg8AQcilAwugB/v//08cNJasKc1gn5V2/DYuRnl4b6NuZi/fB5rBdwoOBgAAoHfBS5dno1jasnE38S4SCAlHouFR+sApR7HWWSKL79yelz11fyCRR7EsFz9fbmwJdHlisY3PCME5NXs3Kz98rbXiSq34voXLg//GYC33KZRdK/122anZmj/nfEAkA48vdHx9tvTMaNBj3C0baGpX+xvvvOWM/jy20lEpfBZkTFe/sfcUIvJ9MfcvI/kozXWtsKiEdeUDbRfcWfuBK0KecG6u8VG1znHA3RMpmJsOBYBC6VZzZO31B/wGuNMJgFNdsQYNFKuXWzG8zDovjE+ZBJIlN1l4NCbiWfDzshwAnKOeMZOPf4JXzPlZECV7fFP7zWe9g1asm6gYrsbsFzMECZKPksjJo/TZf6YBR9mLJ4/9+1Xmzt4OLRdwRY4VE6UgZnX5WZ2ZVwHqo0XnM2zdv2C/4paJx+I1twLvpiIudgBd/OlRSeWuZMGCrX128iJOQvGv4V+XE7D47etlI9kBPlZnQaSjJboMUrpemCwhbXCfkuALYy7ljTRjrYwPGmYZCIlu6JiUND20wnGJpQyvbkFNfcvYJ1nvfCLUBAERlgf+kG8TKjJxjFo7lZGQN1CWNzfy380mlBQCXqEpDNRyDoJMZGltDMJyc8g9YzCdm1pCQQw7VxcnCqB/QlgeELjTUZK0AZScwI809Zg83oOT1AeLGbXPYwx/RlvO7CngQ+GA5vdXj3vbSsX5Loork99rO4/jEMoAAl1nXrctKecj6qy4yOYv8R6NjwW1zvfwzRJ8H4QnUTCoubd9byIhzi1+AHOxdSTqeQVkX6otYtxn8e7Xdq71fylqiLEQ7iUzR54WRLPrASD4tYlq3XaJ3TQOTAP7n6IA4mGcFayzGX0R+krdZAdiV5Mti3GsHJG6+FYYISp3CMFg9aFV9WgXZIs6zEmo7UWQbqVH9LpafStbw6/v4Ua/Pkg47qP9/RfvaMRqvM7HsG9Jryf2s34eEapUzcyjkkpfuMOubR1HFMwGf4lFmV7tafi5x3bRxWN5uYLSR51EFtxVzV1/hyoj2h08y2o/HLkYoHNUZKTEngzfD2tkXfnp9i7EyNy6ei9uxcz31cVAdqfy89gf8xbnR/8w9Pae3HbbOE42ZfQcIrN9xQ6tQO/ha7dA7s7CGs1m0ftNi8+MHDB7M+wTiPEQuP45tsXHMpaZ8g8NQONcmNjssAEAiN2yKc6YbQ0HaR0AQeisAwugB/v//08cNJasKc1gn5V2/DYuRnl4b6NuZi/fB5rBdwoO/v//H9gUPHjdHo0Mby+Yr0VP/fySdF+PrL+cPRpjNx////8PbAoevG6PRoa3F8zXoqd+fkm6r0fWX84ejbGbDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAQYi0AwuAAgCAQMAgoGDgEJBQ0DCwcPAIiEjIKKho6BiYWNg4uHj4BIRExCSkZOQUlFTUNLR09AyMTMwsrGzsHJxc3Dy8fPwCgkLCIqJi4hKSUtIysnLyCopKyiqqauoamlraOrp6+gaGRsYmpmbmFpZW1ja2dvYOjk7OLq5u7h6eXt4+vn7+AYFBwSGhYeERkVHRMbFx8QmJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVdU1tXX1DY1NzS2tbe0dnV3dPb19/QODQ8Mjo2PjE5NT0zOzc/MLi0vLK6tr6xubW9s7u3v7B4dHxyenZ+cXl1fXN7d39w+PT88vr2/vH59f3z+/f/8AQci3Awsgqu/tEolIw2hPv6pyaH8IjTESCAlHouFR+sApR7HWWSIAQcjJBguAAgAAAAIABAQGAAgICggMDAwAEBASEBQUFBAYGBgYGBgcACAgIiAkJCQgKCgoKCgoLCAwMDAwMDA0MDAwODA4ODgAQEBCQEREREBISEhISEhMQFBQUFBQUFRQUFBYUFhYWEBgYGBgYGBkYGBgaGBoaGhgYGBwYHBwcGBwcHBwcHB4AICAgoCEhISAiIiIiIiIjICQkJCQkJCUkJCQmJCYmJiAoKCgoKCgpKCgoKigqKiooKCgsKCwsLCgsLCwsLCwuIDAwMDAwMDEwMDAyMDIyMjAwMDQwNDQ0MDQ0NDQ0NDYwMDA4MDg4ODA4ODg4ODg6MDg4ODg4ODw4ODg8ODw8PAAQcjLBguAAgAAAAEAAQIBAAECAQQBAgMAAQIBBAECAwgBAgMEBQYDAAECAQQBAgMIAQIDBAUGAxABAgMEBQYDCAkKAwwFBgcAAQIBBAECAwgBAgMEBQYDEAECAwQFBgMICQoDDAUGByABAgMEBQYDCAkKAwwFBgcQERIDFAUGBxgJCgsMDQ4HAAECAQQBAgMIAQIDBAUGAxABAgMEBQYDCAkKAwwFBgcgAQIDBAUGAwgJCgMMBQYHEBESAxQFBgcYCQoLDA0OB0ABAgMEBQYDCAkKAwwFBgcQERIDFAUGBxgJCgsMDQ4HICEiAyQFBgcoCQoLDA0OBzAREhMUFRYHGBkaCxwNDg8=", "base64"); + exports.pq = 1000; + exports.pr = 1768; + + +/***/ }), + +/***/ 9565: +/***/ ((module, exports, __webpack_require__) => { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + } + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + } + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + } + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + } + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + } + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + } + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + } + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + } + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + } + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + } + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + } + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + } + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + } + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, t, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2))); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + } + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + } + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + } + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b) { + a = parseValue(a); + b = parseValue(b); + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(Math.random() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] : BASE; + var digit = truncate(Math.random() * top); + result.push(digit); + if (digit < top) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + } + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; +})(); + +// Node.js check +if ( true && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +//amd check +if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return bigInt; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); +} + + +/***/ }), + +/***/ 36336: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +/* + Copyright 2019 0KIMS association. + + This file is part of websnark (Web Assembly zkSnark Prover). + + websnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + websnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with websnark. If not, see . +*/ + +/* globals WebAssembly, Blob, Worker, navigator, Promise, window */ +const bigInt = __webpack_require__(9565); +const groth16_wasm = __webpack_require__(71293); +const assert = __webpack_require__(94148); + +const inBrowser = (typeof window !== "undefined"); +let NodeWorker; +let NodeCrypto; +if (!inBrowser) { + NodeWorker = (__webpack_require__(5183).Worker); + NodeCrypto = __webpack_require__(91565); +} + + +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject)=> { + this.reject = reject; + this.resolve = resolve; + }); + } +} + +/* +function delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} +*/ + +function thread(self) { + let instance; + let memory; + let i32; + + async function init(data) { + const code = new Uint8Array(data.code); + const wasmModule = await WebAssembly.compile(code); + memory = new WebAssembly.Memory({initial:data.init}); + i32 = new Uint32Array(memory.buffer); + + instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": memory + } + }); + } + + function alloc(length) { + while (i32[0] & 3) i32[0]++; // Return always aligned pointers + const res = i32[0]; + i32[0] += length; + while (i32[0] > memory.buffer.byteLength) { + memory.grow(100); + } + i32 = new Uint32Array(memory.buffer); + return res; + } + + function putBin(b) { + const p = alloc(b.byteLength); + const s32 = new Uint32Array(b); + i32.set(s32, p/4); + return p; + } + + function getBin(p, l) { + return memory.buffer.slice(p, p+l); + } + + self.onmessage = function(e) { + let data; + if (e.data) { + data = e.data; + } else { + data = e; + } + + if (data.command == "INIT") { + init(data).then(function() { + self.postMessage(data.result); + }); + } else if (data.command == "G1_MULTIEXP") { + + const oldAlloc = i32[0]; + const pScalars = putBin(data.scalars); + const pPoints = putBin(data.points); + const pRes = alloc(96); + instance.exports.g1_zero(pRes); + instance.exports.g1_multiexp2(pScalars, pPoints, data.n, 7, pRes); + + data.result = getBin(pRes, 96); + i32[0] = oldAlloc; + self.postMessage(data.result, [data.result]); + } else if (data.command == "G2_MULTIEXP") { + + const oldAlloc = i32[0]; + const pScalars = putBin(data.scalars); + const pPoints = putBin(data.points); + const pRes = alloc(192); + instance.exports.g2_zero(pRes); + instance.exports.g2_multiexp(pScalars, pPoints, data.n, 7, pRes); + + data.result = getBin(pRes, 192); + i32[0] = oldAlloc; + self.postMessage(data.result, [data.result]); + } else if (data.command == "CALC_H") { + const oldAlloc = i32[0]; + const pSignals = putBin(data.signals); + const pPolsA = putBin(data.polsA); + const pPolsB = putBin(data.polsB); + const nSignals = data.nSignals; + const domainSize = data.domainSize; + const pSignalsM = alloc(nSignals*32); + const pPolA = alloc(domainSize*32); + const pPolB = alloc(domainSize*32); + const pPolA2 = alloc(domainSize*32*2); + const pPolB2 = alloc(domainSize*32*2); + + instance.exports.fft_toMontgomeryN(pSignals, pSignalsM, nSignals); + + instance.exports.pol_zero(pPolA, domainSize); + instance.exports.pol_zero(pPolB, domainSize); + + instance.exports.pol_constructLC(pPolsA, pSignalsM, nSignals, pPolA); + instance.exports.pol_constructLC(pPolsB, pSignalsM, nSignals, pPolB); + + instance.exports.fft_copyNInterleaved(pPolA, pPolA2, domainSize); + instance.exports.fft_copyNInterleaved(pPolB, pPolB2, domainSize); + + instance.exports.fft_ifft(pPolA, domainSize, 0); + instance.exports.fft_ifft(pPolB, domainSize, 0); + instance.exports.fft_fft(pPolA, domainSize, 1); + instance.exports.fft_fft(pPolB, domainSize, 1); + + instance.exports.fft_copyNInterleaved(pPolA, pPolA2+32, domainSize); + instance.exports.fft_copyNInterleaved(pPolB, pPolB2+32, domainSize); + + instance.exports.fft_mulN(pPolA2, pPolB2, domainSize*2, pPolA2); + + instance.exports.fft_ifft(pPolA2, domainSize*2, 0); + + instance.exports.fft_fromMontgomeryN(pPolA2+domainSize*32, pPolA2+domainSize*32, domainSize); + + data.result = getBin(pPolA2+domainSize*32, domainSize*32); + i32[0] = oldAlloc; + self.postMessage(data.result, [data.result]); + } else if (data.command == "TERMINATE") { + process.exit(); + } + }; +} + +// We use the Object.assign approach for the backwards compatibility +// @params Number wasmInitialMemory +async function build(params) { + const defaultParams = { wasmInitialMemory: 5000 }; + Object.assign(defaultParams, params); + const groth16 = new Groth16(); + + groth16.q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"); + groth16.r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + groth16.n64 = Math.floor((groth16.q.minus(1).bitLength() - 1)/64) +1; + groth16.n32 = groth16.n64*2; + groth16.n8 = groth16.n64*8; + + groth16.memory = new WebAssembly.Memory({initial:defaultParams.wasmInitialMemory}); + groth16.i32 = new Uint32Array(groth16.memory.buffer); + + const wasmModule = await WebAssembly.compile(groth16_wasm.code); + + groth16.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": groth16.memory + } + }); + + groth16.pq = groth16_wasm.pq; + groth16.pr = groth16_wasm.pr; + + groth16.pr0 = groth16.alloc(192); + groth16.pr1 = groth16.alloc(192); + + groth16.workers = []; + groth16.pendingDeferreds = []; + groth16.working = []; + + let concurrency; + + if ((typeof(navigator) === "object") && navigator.hardwareConcurrency) { + concurrency = navigator.hardwareConcurrency; + } else { + concurrency = 8; + } + + function getOnMsg(i) { + return function(e) { + let data; + if ((e)&&(e.data)) { + data = e.data; + } else { + data = e; + } + + groth16.working[i]=false; + groth16.pendingDeferreds[i].resolve(data); + groth16.processWorks(); + }; + } + + for (let i = 0; i 0); i++) { + if (this.working[i] == false) { + const work = this.actionQueue.shift(); + this.postAction(i, work.data, work.transfers, work.deferred); + } + } + } + + queueAction(actionData, transfers) { + const d = new Deferred(); + this.actionQueue.push({ + data: actionData, + transfers: transfers, + deferred: d + }); + this.processWorks(); + return d.promise; + } + + alloc(length) { + while (this.i32[0] & 3) this.i32[0]++; // Return always aligned pointers + const res = this.i32[0]; + this.i32[0] += length; + return res; + } + + + putBin(p, b) { + const s32 = new Uint32Array(b); + this.i32.set(s32, p/4); + } + + getBin(p, l) { + return this.memory.buffer.slice(p, p+l); + } + + bin2int(b) { + const i32 = new Uint32Array(b); + let acc = bigInt(i32[7]); + for (let i=6; i>=0; i--) { + acc = acc.shiftLeft(32); + acc = acc.add(i32[i]); + } + return acc.toString(); + } + + bin2g1(b) { + return [ + this.bin2int(b.slice(0,32)), + this.bin2int(b.slice(32,64)), + this.bin2int(b.slice(64,96)), + ]; + } + bin2g2(b) { + return [ + [ + this.bin2int(b.slice(0,32)), + this.bin2int(b.slice(32,64)) + ], + [ + this.bin2int(b.slice(64,96)), + this.bin2int(b.slice(96,128)) + ], + [ + this.bin2int(b.slice(128,160)), + this.bin2int(b.slice(160,192)) + ], + ]; + } + + async g1_multiexp(scalars, points) { + const nPoints = scalars.byteLength /32; + const nPointsPerThread = Math.floor(nPoints / this.workers.length); + const opPromises = []; + for (let i=0; i { + /* Debug code to print the result of h + for (let i=0; i " + a.toString()); + } +*/ + return this.g1_multiexp(h, pointsHExps); + }); + + const pA = this.g1_multiexp(signals.slice(0), pointsA); + const pB1 = this.g1_multiexp(signals.slice(0), pointsB1); + const pB2 = this.g2_multiexp(signals.slice(0), pointsB2); + const pC = this.g1_multiexp(signals.slice((nPublic+1)*32), pointsC); + + const res = await Promise.all([pA, pB1, pB2, pC, pH]); + + const pi_a = this.alloc(96); + const pi_b = this.alloc(192); + const pi_c = this.alloc(96); + const pib1 = this.alloc(96); + + + this.putBin(pi_a, res[0]); + this.putBin(pib1, res[1]); + this.putBin(pi_b, res[2]); + this.putBin(pi_c, res[3]); + + const pAlfa1 = this.loadPoint1(alfa1); + const pBeta1 = this.loadPoint1(beta1); + const pDelta1 = this.loadPoint1(delta1); + const pBeta2 = this.loadPoint2(beta2); + const pDelta2 = this.loadPoint2(delta2); + + + let rnd = new Uint32Array(8); + + const aux1 = this.alloc(96); + const aux2 = this.alloc(192); + + const pr = this.alloc(32); + const ps = this.alloc(32); + + if (inBrowser) { + window.crypto.getRandomValues(rnd); + this.putBin(pr, rnd); + + window.crypto.getRandomValues(rnd); + this.putBin(ps, rnd); + } else { + const br = NodeCrypto.randomBytes(32); + this.putBin(pr, br); + const bs = NodeCrypto.randomBytes(32); + this.putBin(ps, bs); + } + + /// Uncoment it to debug and check it works + // this.instance.exports.f1m_zero(pr); + // this.instance.exports.f1m_zero(ps); + + // pi_a = pi_a + Alfa1 + r*Delta1 + this.instance.exports.g1_add(pAlfa1, pi_a, pi_a); + this.instance.exports.g1_timesScalar(pDelta1, pr, 32, aux1); + this.instance.exports.g1_add(aux1, pi_a, pi_a); + + // pi_b = pi_b + Beta2 + s*Delta2 + this.instance.exports.g2_add(pBeta2, pi_b, pi_b); + this.instance.exports.g2_timesScalar(pDelta2, ps, 32, aux2); + this.instance.exports.g2_add(aux2, pi_b, pi_b); + + // pib1 = pib1 + Beta1 + s*Delta1 + this.instance.exports.g1_add(pBeta1, pib1, pib1); + this.instance.exports.g1_timesScalar(pDelta1, ps, 32, aux1); + this.instance.exports.g1_add(aux1, pib1, pib1); + + + // pi_c = pi_c + pH + this.putBin(aux1, res[4]); + this.instance.exports.g1_add(aux1, pi_c, pi_c); + + + // pi_c = pi_c + s*pi_a + this.instance.exports.g1_timesScalar(pi_a, ps, 32, aux1); + this.instance.exports.g1_add(aux1, pi_c, pi_c); + + // pi_c = pi_c + r*pib1 + this.instance.exports.g1_timesScalar(pib1, pr, 32, aux1); + this.instance.exports.g1_add(aux1, pi_c, pi_c); + + // pi_c = pi_c - r*s*delta1 + const prs = this.alloc(64); + this.instance.exports.int_mul(pr, ps, prs); + this.instance.exports.g1_timesScalar(pDelta1, prs, 64, aux1); + this.instance.exports.g1_neg(aux1, aux1); + this.instance.exports.g1_add(aux1, pi_c, pi_c); + + this.instance.exports.g1_affine(pi_a, pi_a); + this.instance.exports.g2_affine(pi_b, pi_b); + this.instance.exports.g1_affine(pi_c, pi_c); + + this.instance.exports.g1_fromMontgomery(pi_a, pi_a); + this.instance.exports.g2_fromMontgomery(pi_b, pi_b); + this.instance.exports.g1_fromMontgomery(pi_c, pi_c); + + return { + pi_a: this.bin2g1(this.getBin(pi_a, 96)), + pi_b: this.bin2g2(this.getBin(pi_b, 192)), + pi_c: this.bin2g1(this.getBin(pi_c, 96)), + }; + + } + +} + +module.exports = build; + + +/***/ }), + +/***/ 84276: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of websnark (Web Assembly zkSnark Prover). + + websnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + websnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with websnark. If not, see . +*/ + +const bigInt = __webpack_require__(9565); +const Circuit = __webpack_require__(98665); +const bigInt2 = __webpack_require__(27351); +const hexifyBigInts = (__webpack_require__(56274)/* .hexifyBigInts */ .cL); +const unhexifyBigInts = (__webpack_require__(56274)/* .unhexifyBigInts */ .XL); +const stringifyBigInts = (__webpack_require__(56274)/* .stringifyBigInts */ .ex); +const unstringifyBigInts = (__webpack_require__(56274)/* .unstringifyBigInts */ .Hf); +const stringifyBigInts2 = (__webpack_require__(73248)/* .stringifyBigInts */ .e); +const unstringifyBigInts2 = (__webpack_require__(73248)/* .unstringifyBigInts */ .H); + +function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = bigInt(_a); + for (let i = 0; i < len; i++) { + b[i] = v.and(0xff).toJSNumber(); + v = v.shiftRight(8); + } + return b; +} + +function bigInt2U32LE(_a, len) { + const b = Array(len); + let v = bigInt(_a); + for (let i = 0; i < len; i++) { + b[i] = v.and(0xffffffff).toJSNumber(); + v = v.shiftRight(32); + } + return b; +} + +function convertWitness(witness) { + const buffLen = witness.length * 32; + const buff = new ArrayBuffer(buffLen); + const h = { + dataView: new DataView(buff), + offset: 0, + }; + const mask = bigInt2(0xffffffff); + for (let i = 0; i < witness.length; i++) { + for (let j = 0; j < 8; j++) { + const v = Number(witness[i].shr(j * 32).and(mask)); + h.dataView.setUint32(h.offset, v, true); + h.offset += 4; + } + } + return buff; +} + +function toHex32(number) { + let str = number.toString(16); + while (str.length < 64) str = "0" + str; + return str; +} + +function toSolidityInput(proof) { + const flatProof = unstringifyBigInts([ + proof.pi_a[0], + proof.pi_a[1], + proof.pi_b[0][1], + proof.pi_b[0][0], + proof.pi_b[1][1], + proof.pi_b[1][0], + proof.pi_c[0], + proof.pi_c[1], + ]); + const result = { + proof: "0x" + flatProof.map((x) => toHex32(x)).join(""), + }; + if (proof.publicSignals) { + result.publicSignals = hexifyBigInts(unstringifyBigInts(proof.publicSignals)); + } + return result; +} + +function genWitness(input, circuitJson) { + const circuit = new Circuit(unstringifyBigInts2(circuitJson)); + const witness = circuit.calculateWitness(unstringifyBigInts2(input)); + const publicSignals = witness.slice(1, circuit.nPubInputs + circuit.nOutputs + 1); + return { witness, publicSignals }; +} + +async function genWitnessAndProve(groth16, input, circuitJson, provingKey) { + const witnessData = genWitness(input, circuitJson); + const witnessBin = convertWitness(witnessData.witness); + const result = await groth16.proof(witnessBin, provingKey); + result.publicSignals = stringifyBigInts2(witnessData.publicSignals); + return result; +} + +module.exports = { bigInt2BytesLE, bigInt2U32LE, toSolidityInput, genWitnessAndProve }; + + +/***/ }), + +/***/ 56274: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + +const bigInt = __webpack_require__(9565); + +module.exports.ex = stringifyBigInts; +module.exports.Hf = unstringifyBigInts; +module.exports.cL = hexifyBigInts; +module.exports.XL = unhexifyBigInts; + +function stringifyBigInts(o) { + if ((typeof(o) == "bigint") || (o instanceof bigInt)) { + return o.toString(10); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + for (let k in o) { + res[k] = stringifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + +function unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return bigInt(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts); + } else if (typeof o == "object" && !(o instanceof bigInt)) { + const res = {}; + for (let k in o) { + res[k] = unstringifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + +function hexifyBigInts(o) { + if (typeof (o) === "bigInt" || (o instanceof bigInt)) { + let str = o.toString(16); + while (str.length < 64) str = "0" + str; + str = "0x" + str; + return str; + } else if (Array.isArray(o)) { + return o.map(hexifyBigInts); + } else if (typeof o == "object") { + const res = {}; + for (let k in o) { + res[k] = hexifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + +function unhexifyBigInts(o) { + if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o))) { + return bigInt(o); + } else if (Array.isArray(o)) { + return o.map(unhexifyBigInts); + } else if (typeof o == "object") { + const res = {}; + for (let k in o) { + res[k] = unhexifyBigInts(o[k]); + } + return res; + } else { + return o; + } +} + + +/***/ }), + +/***/ 63282: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; +const core_1 = __webpack_require__(4042); +const draft7_1 = __webpack_require__(86144); +const discriminator_1 = __webpack_require__(36653); +const draft7MetaSchema = __webpack_require__(72079); +const META_SUPPORT_DATA = ["/properties"]; +const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; +class Ajv extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data + ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) + : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } +} +module.exports = exports = Ajv; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = Ajv; +var validate_1 = __webpack_require__(62586); +Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } })); +var codegen_1 = __webpack_require__(99029); +Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } })); +Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } })); +Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } })); +Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } })); +Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } })); +Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } })); +var validation_error_1 = __webpack_require__(13558); +Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } })); +var ref_error_1 = __webpack_require__(34551); +Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } })); +//# sourceMappingURL=ajv.js.map + +/***/ }), + +/***/ 41520: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; +class _CodeOrName { +} +exports._CodeOrName = _CodeOrName; +exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +class Name extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } +} +exports.Name = Name; +class _Code extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a; + return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); + } + get names() { + var _a; + return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { + if (c instanceof Name) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}))); + } +} +exports._Code = _Code; +exports.nil = new _Code(""); +function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); +} +exports._ = _; +const plus = new _Code("+"); +function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); +} +exports.str = str; +function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); +} +exports.addCodeArg = addCodeArg; +function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== undefined) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } +} +function mergeExprItems(a, b) { + if (b === '""') + return a; + if (a === '""') + return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b != "string") + return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') + return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) + return `"${a}${b.slice(1)}`; + return; +} +function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; +} +exports.strConcat = strConcat; +// TODO do not allow arrays here +function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x); +} +function stringify(x) { + return new _Code(safeStringify(x)); +} +exports.stringify = stringify; +function safeStringify(x) { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029"); +} +exports.safeStringify = safeStringify; +function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; +} +exports.getProperty = getProperty; +//Does best effort to format the name properly +function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); +} +exports.getEsmExportName = getEsmExportName; +function regexpCode(rx) { + return new _Code(rx.toString()); +} +exports.regexpCode = regexpCode; +//# sourceMappingURL=code.js.map + +/***/ }), + +/***/ 99029: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; +const code_1 = __webpack_require__(41520); +const scope_1 = __webpack_require__(57845); +var code_2 = __webpack_require__(41520); +Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return code_2._; } })); +Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return code_2.str; } })); +Object.defineProperty(exports, "strConcat", ({ enumerable: true, get: function () { return code_2.strConcat; } })); +Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return code_2.nil; } })); +Object.defineProperty(exports, "getProperty", ({ enumerable: true, get: function () { return code_2.getProperty; } })); +Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return code_2.stringify; } })); +Object.defineProperty(exports, "regexpCode", ({ enumerable: true, get: function () { return code_2.regexpCode; } })); +Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return code_2.Name; } })); +var scope_2 = __webpack_require__(57845); +Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return scope_2.Scope; } })); +Object.defineProperty(exports, "ValueScope", ({ enumerable: true, get: function () { return scope_2.ValueScope; } })); +Object.defineProperty(exports, "ValueScopeName", ({ enumerable: true, get: function () { return scope_2.ValueScopeName; } })); +Object.defineProperty(exports, "varKinds", ({ enumerable: true, get: function () { return scope_2.varKinds; } })); +exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+"), +}; +class Node { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } +} +class Def extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } +} +class Assign extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } +} +class AssignOp extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } +} +class Label extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } +} +class Break extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } +} +class Throw extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } +} +class AnyCode extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : undefined; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } +} +class ParentNode extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i, 1, ...n); + else if (n) + nodes[i] = n; + else + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } +} +class BlockNode extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } +} +class Root extends ParentNode { +} +class Else extends BlockNode { +} +Else.kind = "else"; +class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; // else is ignored here + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) + return e instanceof If ? e : e.nodes; + if (this.nodes.length) + return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) + return undefined; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } +} +If.kind = "if"; +class For extends BlockNode { +} +For.kind = "for"; +class ForLoop extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } +} +class ForRange extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } +} +class ForIter extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } +} +class Func extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } +} +Func.kind = "func"; +class Return extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } +} +Return.kind = "return"; +class Try extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } +} +class Catch extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } +} +Catch.kind = "catch"; +class Finally extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } +} +Finally.kind = "finally"; +class CodeGen { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== undefined && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } + else if (thenBody) { + this.code(thenBody).endIf(); + } + else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { + this.var(name, (0, code_1._) `${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error) { + return this._leafNode(new Throw(error)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === undefined) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } +} +exports.CodeGen = CodeGen; +function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; +} +function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; +} +function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === undefined || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return (e instanceof code_1._Code && + e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); + } +} +function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); +} +function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; +} +exports.not = not; +const andCode = mappend(exports.operators.AND); +// boolean AND (&&) expression with the passed arguments +function and(...args) { + return args.reduce(andCode); +} +exports.and = and; +const orCode = mappend(exports.operators.OR); +// boolean OR (||) expression with the passed arguments +function or(...args) { + return args.reduce(orCode); +} +exports.or = or; +function mappend(op) { + return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); +} +function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 57845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; +const code_1 = __webpack_require__(41520); +class ValueError extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } +} +var UsedValueState; +(function (UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; +})(UsedValueState = exports.UsedValueState || (exports.UsedValueState = {})); +exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var"), +}; +class Scope { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return (this._names[prefix] = { prefix, index: 0 }); + } +} +exports.Scope = Scope; +class ValueScopeName extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; + } +} +exports.ValueScopeName = ValueScopeName; +const line = (0, code_1._) `\n`; +class ValueScope extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === undefined) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } + else { + vs = this._values[prefix] = new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._) `${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; + } + else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { + code = (0, code_1._) `${code}${c}${this.opts._n}`; + } + else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } +} +exports.ValueScope = ValueScope; +//# sourceMappingURL=scope.js.map + +/***/ }), + +/***/ 48708: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const names_1 = __webpack_require__(42023); +exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, +}; +exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType + ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` + : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, +}; +function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { + addError(gen, errObj); + } + else { + returnErrors(it, (0, codegen_1._) `[${errObj}]`); + } +} +exports.reportError = reportError; +function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } +} +exports.reportExtraError = reportExtraError; +function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); +} +exports.resetErrorsCount = resetErrorsCount; +function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { + /* istanbul ignore if */ + if (errsCount === undefined) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); + gen.assign((0, codegen_1._) `${err}.data`, data); + } + }); +} +exports.extendErrors = extendErrors; +function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._) `${names_1.default.errors}++`); +} +function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, errs); + gen.return(false); + } +} +const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema"), +}; +function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._) `{}`; + return errorObject(cxt, error, errorPaths); +} +function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); +} +function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath + ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` + : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; +} +function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E.schemaPath, schPath]; +} +function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); +} +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 73835: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; +const codegen_1 = __webpack_require__(99029); +const validation_error_1 = __webpack_require__(13558); +const names_1 = __webpack_require__(42023); +const resolve_1 = __webpack_require__(66939); +const util_1 = __webpack_require__(94227); +const validate_1 = __webpack_require__(62586); +class SchemaEnv { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } +} +exports.SchemaEnv = SchemaEnv; +// let codeSize = 0 +// let nodeCount = 0 +// Compiles schema in SchemaEnv +function compileSchema(sch) { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`, + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true + ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } + : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._) `""`, + opts: this.opts, + self: this, + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + // gen.optimize(1) + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? undefined : props, + items: items instanceof codegen_1.Name ? undefined : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name, + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } + catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e; + } + finally { + this._compilations.delete(sch); + } +} +exports.compileSchema = compileSchema; +function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === undefined) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === undefined) + return; + return (root.refs[ref] = inlineOrCompile.call(this, _sch)); +} +exports.resolveRef = resolveRef; +function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); +} +// Index of schema compilation in the currently compiled list +function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } +} +exports.getCompilingSchema = getCompilingSchema; +function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; +} +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve(root, // information about the root schema for the current schema +ref // reference to resolve +) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); +} +// Resolve schema, its root and baseId +function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it +ref // reference to resolve +) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p, schOrRef); +} +exports.resolveSchema = resolveSchema; +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]); +function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === undefined) + return; + schema = partSchema; + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return undefined; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 42023: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const names = { + // validation function arguments + data: new codegen_1.Name("data"), + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart"), +}; +exports["default"] = names; +//# sourceMappingURL=names.js.map + +/***/ }), + +/***/ 34551: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const resolve_1 = __webpack_require__(66939); +class MissingRefError extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } +} +exports["default"] = MissingRefError; +//# sourceMappingURL=ref_error.js.map + +/***/ }), + +/***/ 66939: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; +const util_1 = __webpack_require__(94227); +const equal = __webpack_require__(32017); +const traverse = __webpack_require__(7106); +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]); +function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; +} +exports.inlineRef = inlineRef; +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]); +function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; +} +function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch))); + } + if (count === Infinity) + return Infinity; + } + return count; +} +function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); +} +exports.getFullPath = getFullPath; +function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; +} +exports._getFullPath = _getFullPath; +const TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; +} +exports.normalizeId = normalizeId; +function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); +} +exports.resolveUrl = resolveUrl; +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; +function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) + return; + const fullPath = pathPrefix + jsonPtr; + let baseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + baseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = baseId; + function addRef(ref) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(baseId ? _resolve(baseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } + else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } + else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== undefined && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } +} +exports.getSchemaRefs = getSchemaRefs; +//# sourceMappingURL=resolve.js.map + +/***/ }), + +/***/ 10396: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRules = exports.isJSONType = void 0; +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; +const jsonTypes = new Set(_jsonTypes); +function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); +} +exports.isJSONType = isJSONType; +function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] }, + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {}, + }; +} +exports.getRules = getRules; +//# sourceMappingURL=rules.js.map + +/***/ }), + +/***/ 94227: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; +const codegen_1 = __webpack_require__(99029); +const code_1 = __webpack_require__(41520); +// TODO refactor to use Set +function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; +} +exports.toHash = toHash; +function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); +} +exports.alwaysValidSchema = alwaysValidSchema; +function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } +} +exports.checkUnknownRules = checkUnknownRules; +function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; +} +exports.schemaHasRules = schemaHasRules; +function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; +} +exports.schemaHasRulesButRef = schemaHasRulesButRef; +function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._) `${schema}`; + } + return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; +} +exports.schemaRefOrVal = schemaRefOrVal; +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); +} +exports.unescapeFragment = unescapeFragment; +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} +exports.escapeFragment = escapeFragment; +function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); +} +exports.escapeJsonPointer = escapeJsonPointer; +function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); +} +exports.unescapeJsonPointer = unescapeJsonPointer; +function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } + else { + f(xs); + } +} +exports.eachItem = eachItem; +function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { + return (gen, from, to, toName) => { + const res = to === undefined + ? from + : to instanceof codegen_1.Name + ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof codegen_1.Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; +} +exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } + else { + gen.assign(to, (0, codegen_1._) `${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), +}; +function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._) `{}`); + if (ps !== undefined) + setEvaluated(gen, props, ps); + return props; +} +exports.evaluatedPropsToName = evaluatedPropsToName; +function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); +} +exports.setEvaluated = setEvaluated; +const snippets = {}; +function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), + }); +} +exports.useFunc = useFunc; +var Type; +(function (Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; +})(Type = exports.Type || (exports.Type = {})); +function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + // let path + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax + ? isNumber + ? (0, codegen_1._) `"[" + ${dataProp} + "]"` + : (0, codegen_1._) `"['" + ${dataProp} + "']"` + : isNumber + ? (0, codegen_1._) `"/" + ${dataProp}` + : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); +} +exports.getErrorPath = getErrorPath; +function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); +} +exports.checkStrictMode = checkStrictMode; +//# sourceMappingURL=util.js.map + +/***/ }), + +/***/ 7887: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; +function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); +} +exports.schemaHasRulesForType = schemaHasRulesForType; +function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); +} +exports.shouldUseGroup = shouldUseGroup; +function shouldUseRule(schema, rule) { + var _a; + return (schema[rule.keyword] !== undefined || + ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); +} +exports.shouldUseRule = shouldUseRule; +//# sourceMappingURL=applicability.js.map + +/***/ }), + +/***/ 28727: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; +const errors_1 = __webpack_require__(48708); +const codegen_1 = __webpack_require__(99029); +const names_1 = __webpack_require__(42023); +const boolError = { + message: "boolean schema is false", +}; +function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } + else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, null); + gen.return(true); + } +} +exports.topBoolOrEmptySchema = topBoolOrEmptySchema; +function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); // TODO var + falseSchemaError(it); + } + else { + gen.var(valid, true); // TODO var + } +} +exports.boolOrEmptySchema = boolOrEmptySchema; +function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + }; + (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); +} +//# sourceMappingURL=boolSchema.js.map + +/***/ }), + +/***/ 10208: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; +const rules_1 = __webpack_require__(10396); +const applicability_1 = __webpack_require__(7887); +const errors_1 = __webpack_require__(48708); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +var DataType; +(function (DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; +})(DataType = exports.DataType || (exports.DataType = {})); +function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } + else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; +} +exports.getSchemaTypes = getSchemaTypes; +function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); +} +exports.getJSONTypes = getJSONTypes; +function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; +} +exports.coerceAndCheckDataType = coerceAndCheckDataType; +const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); +function coerceToTypes(types, coerceTypes) { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : []; +} +function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen + .assign(data, (0, codegen_1._) `${data}[0]`) + .assign(dataType, (0, codegen_1._) `typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._) `${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen + .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, (0, codegen_1._) `"" + ${data}`) + .elseIf((0, codegen_1._) `${data} === null`) + .assign(coerced, (0, codegen_1._) `""`); + return; + case "number": + gen + .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "integer": + gen + .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "boolean": + gen + .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) + .assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen + .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`) + .assign(coerced, (0, codegen_1._) `[${data}]`); + } + } +} +function assignParentData({ gen, parentData, parentDataProperty }, expr) { + // TODO use gen.property + gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); +} +function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._) `${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._) `Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); + } +} +exports.checkDataType = checkDataType; +function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._) `typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } + else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t in types) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; +} +exports.checkDataTypes = checkDataTypes; +const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, +}; +function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); +} +exports.reportTypeError = reportTypeError; +function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + }; +} +//# sourceMappingURL=dataType.js.map + +/***/ }), + +/***/ 7870: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assignDefaults = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } + else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } +} +exports.assignDefaults = assignDefaults; +function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === undefined) + return; + const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._) `${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); +} +//# sourceMappingURL=defaults.js.map + +/***/ }), + +/***/ 62586: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; +const boolSchema_1 = __webpack_require__(28727); +const dataType_1 = __webpack_require__(10208); +const applicability_1 = __webpack_require__(7887); +const dataType_2 = __webpack_require__(10208); +const defaults_1 = __webpack_require__(7870); +const keyword_1 = __webpack_require__(33673); +const subschema_1 = __webpack_require__(24495); +const codegen_1 = __webpack_require__(99029); +const names_1 = __webpack_require__(42023); +const resolve_1 = __webpack_require__(66939); +const util_1 = __webpack_require__(94227); +const errors_1 = __webpack_require__(48708); +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); +} +exports.validateFunctionCode = validateFunctionCode; +function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } + else { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } +} +function destructureValCxt(opts) { + return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; +} +function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); + gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); + }); +} +function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; +} +function resetEvaluated(it) { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); +} +function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; +} +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); +} +function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self.RULES.all[key]) + return true; + return false; +} +function isSchemaObj(it) { + return typeof it.schema != "boolean"; +} +function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + // TODO var + gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); +} +function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); +} +function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); +} +function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } +} +function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } +} +function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); +} +function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); +} +function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); + } + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } +} +function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); + } +} +function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.items`, items); +} +function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } + else { + iterateKeywords(it, group); + } + // TODO make it "ok" call? + if (!allErrors) + gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); + } +} +function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults }, } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); +} +function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); +} +function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); +} +function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } +} +function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } +} +function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); +} +function includesType(ts, t) { + return ts.includes(t) || (t === "integer" && ts.includes("number")); +} +function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts.push(t); + else if (withTypes.includes("integer") && t === "number") + ts.push("integer"); + } + it.dataTypes = ts; +} +function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); +} +class KeywordCxt { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } + else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), undefined, failAction); + } + fail(condition) { + if (condition === undefined) { + this.error(); + if (!this.allErrors) + this.gen.if(false); // this branch will be removed by gen.optimize + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === undefined) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone + return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } +} +exports.KeywordCxt = KeywordCxt; +function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } + else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } + else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } +} +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } + else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._) `${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } +} +exports.getData = getData; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 33673: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; +const codegen_1 = __webpack_require__(99029); +const names_1 = __webpack_require__(42023); +const code_1 = __webpack_require__(15765); +const errors_1 = __webpack_require__(48708); +function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, valid); + cxt.pass(valid, () => cxt.error(true)); +} +exports.macroKeywordCode = macroKeywordCode; +function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } + else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._) `${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !(("compile" in def && !$data) || def.schema === false); + gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a; + gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); + } +} +exports.funcKeywordCode = funcKeywordCode; +function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); +} +function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { + gen + .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) + .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); +} +function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); +} +function useKeyword(gen, keyword, result) { + if (result === undefined) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); +} +function validSchemaType(schema, schemaType, allowUndefined = false) { + // TODO add tests + return (!schemaType.length || + schemaType.some((st) => st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); +} +exports.validSchemaType = validSchemaType; +function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self.logger.error(msg); + else + throw new Error(msg); + } + } +} +exports.validateKeywordUsage = validateKeywordUsage; +//# sourceMappingURL=keyword.js.map + +/***/ }), + +/***/ 24495: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== undefined) { + const sch = it.schema[keyword]; + return schemaProp === undefined + ? { + schema: sch, + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, + }; + } + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + }; + } + throw new Error('either "keyword" or "schema" must be passed'); +} +exports.getSubschema = getSubschema; +function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== undefined) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== undefined) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once? + dataContextProps(nextData); + if (propertyName !== undefined) + subschema.propertyName = propertyName; + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } +} +exports.extendSubschemaData = extendSubschemaData; +function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== undefined) + subschema.compositeRule = compositeRule; + if (createErrors !== undefined) + subschema.createErrors = createErrors; + if (allErrors !== undefined) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; // not inherited + subschema.jtdMetadata = jtdMetadata; // not inherited +} +exports.extendSubschemaMode = extendSubschemaMode; +//# sourceMappingURL=subschema.js.map + +/***/ }), + +/***/ 4042: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(96763); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; +var validate_1 = __webpack_require__(62586); +Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } })); +var codegen_1 = __webpack_require__(99029); +Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } })); +Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } })); +Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } })); +Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } })); +Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } })); +Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } })); +const validation_error_1 = __webpack_require__(13558); +const ref_error_1 = __webpack_require__(34551); +const rules_1 = __webpack_require__(10396); +const compile_1 = __webpack_require__(73835); +const codegen_2 = __webpack_require__(99029); +const resolve_1 = __webpack_require__(66939); +const dataType_1 = __webpack_require__(10208); +const util_1 = __webpack_require__(94227); +const $dataRefSchema = __webpack_require__(63837); +const uri_1 = __webpack_require__(55944); +const defaultRegExp = (str, flags) => new RegExp(str, flags); +defaultRegExp.code = "new RegExp"; +const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; +const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error", +]); +const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now.", +}; +const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.', +}; +const MAX_EXPRESSION = 200; +// eslint-disable-next-line complexity +function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver: uriResolver, + }; +} +class Ajv { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = new Set(); + this._loading = {}; + this._cache = new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); + } + validate(schemaKeyRef, // key, ref or schema object + data // to be validated + ) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } + else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return (sch.validate || this._compileSchemaEnv(sch)); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } + catch (e) { + if (!(e instanceof ref_error_1.default)) + throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } + finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, // If array is passed, `key` will be ignored + key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. + ) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, undefined, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== undefined && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, // schema key + _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema + ) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === undefined) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return (sch.validate || this._compileSchemaEnv(sch)); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def // deprecated + ) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } + else if (typeof kwdOrDef == "object" && def === undefined) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } + else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 + ? (k) => addRule.call(this, k, definition) + : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + // TODO return type should be Ajv + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) + group.rules.splice(i, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, // optional array of validation errors + { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar` + ) { + if (!errors || errors.length === 0) + return "No errors"; + return errors + .map((e) => `${dataVar}${e.instancePath} ${e.message}`) + .reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); // first segment is an empty string + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } + else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== undefined) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } + finally { + this.opts = currentOpts; + } + } +} +exports["default"] = Ajv; +Ajv.ValidationError = validation_error_1.default; +Ajv.MissingRefError = ref_error_1.default; +function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } +} +function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line + return this.schemas[keyRef] || this.refs[keyRef]; +} +function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); +} +function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } +} +function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } +} +function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; +} +const noLogs = { log() { }, warn() { }, error() { } }; +function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === undefined) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); +} +const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; +function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } +} +function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), + }, + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); +} +function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule); + } + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } +} +function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === undefined) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); +} +const $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", +}; +function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; +} +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 76250: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// https://github.com/ajv-validator/ajv/issues/889 +const equal = __webpack_require__(32017); +equal.code = 'require("ajv/dist/runtime/equal").default'; +exports["default"] = equal; +//# sourceMappingURL=equal.js.map + +/***/ }), + +/***/ 53853: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xfc00) === 0xdc00) + pos++; // low surrogate + } + } + return length; +} +exports["default"] = ucs2length; +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; +//# sourceMappingURL=ucs2length.js.map + +/***/ }), + +/***/ 55944: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const uri = __webpack_require__(46579); +uri.code = 'require("ajv/dist/runtime/uri").default'; +exports["default"] = uri; +//# sourceMappingURL=uri.js.map + +/***/ }), + +/***/ 13558: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class ValidationError extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } +} +exports["default"] = ValidationError; +//# sourceMappingURL=validation_error.js.map + +/***/ }), + +/***/ 15457: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateAdditionalItems = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, +}; +const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + }, +}; +function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._) `${len} <= ${items.length}`); + } + else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } +} +exports.validateAdditionalItems = validateAdditionalItems; +exports["default"] = def; +//# sourceMappingURL=additionalItems.js.map + +/***/ }), + +/***/ 38660: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const code_1 = __webpack_require__(15765); +const codegen_1 = __webpack_require__(99029); +const names_1 = __webpack_require__(42023); +const util_1 = __webpack_require__(94227); +const error = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`, +}; +const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } + else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`)); + } + else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._) `delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } + else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str, + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }); + } + cxt.subschema(subschema, valid); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=additionalProperties.js.map + +/***/ }), + +/***/ 15844: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __webpack_require__(94227); +const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + }, +}; +exports["default"] = def; +//# sourceMappingURL=allOf.js.map + +/***/ }), + +/***/ 16505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const code_1 = __webpack_require__(15765); +const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" }, +}; +exports["default"] = def; +//# sourceMappingURL=anyOf.js.map + +/***/ }), + +/***/ 12661: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: ({ params: { min, max } }) => max === undefined + ? (0, codegen_1.str) `must contain at least ${min} valid item(s)` + : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`, +}; +const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains; + max = maxContains; + } + else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + cxt.setParams({ min, max }); + if (max === undefined && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== undefined && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._) `${len} >= ${min}`; + if (max !== undefined) + cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } + else if (min === 0) { + gen.let(valid, true); + if (max !== undefined) + gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount); + } + else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true, + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._) `${count}++`); + if (max === undefined) { + gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); + } + else { + gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=contains.js.map + +/***/ }), + +/***/ 83025: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const code_1 = __webpack_require__(15765); +exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +}; +const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + }, +}; +function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; +} +function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } + else { + gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } +} +exports.validatePropertyDeps = validatePropertyDeps; +function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true) // TODO var + ); + cxt.ok(valid); + } +} +exports.validateSchemaDeps = validateSchemaDeps; +exports["default"] = def; +//# sourceMappingURL=dependencies.js.map + +/***/ }), + +/***/ 1239: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`, +}; +const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === undefined && parentSchema.else === undefined) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } + else if (hasThen) { + gen.if(schValid, validateClause("then")); + } + else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._) `${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + }, +}; +function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema); +} +exports["default"] = def; +//# sourceMappingURL=if.js.map + +/***/ }), + +/***/ 56378: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const additionalItems_1 = __webpack_require__(15457); +const prefixItems_1 = __webpack_require__(65354); +const items_1 = __webpack_require__(20494); +const items2020_1 = __webpack_require__(93966); +const contains_1 = __webpack_require__(12661); +const dependencies_1 = __webpack_require__(83025); +const propertyNames_1 = __webpack_require__(19713); +const additionalProperties_1 = __webpack_require__(38660); +const properties_1 = __webpack_require__(40117); +const patternProperties_1 = __webpack_require__(45333); +const not_1 = __webpack_require__(57923); +const anyOf_1 = __webpack_require__(16505); +const oneOf_1 = __webpack_require__(96163); +const allOf_1 = __webpack_require__(15844); +const if_1 = __webpack_require__(1239); +const thenElse_1 = __webpack_require__(14426); +function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default, + ]; + // array + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; +} +exports["default"] = getApplicator; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 20494: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateTuple = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const code_1 = __webpack_require__(15765); +const def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + }, +}; +function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i, + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } +} +exports.validateTuple = validateTuple; +exports["default"] = def; +//# sourceMappingURL=items.js.map + +/***/ }), + +/***/ 93966: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const code_1 = __webpack_require__(15765); +const additionalItems_1 = __webpack_require__(15457); +const error = { + message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, +}; +const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + }, +}; +exports["default"] = def; +//# sourceMappingURL=items2020.js.map + +/***/ }), + +/***/ 57923: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __webpack_require__(94227); +const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" }, +}; +exports["default"] = def; +//# sourceMappingURL=not.js.map + +/***/ }), + +/***/ 96163: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`, +}; +const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } + else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, schValid); + } + if (i > 0) { + gen + .if((0, codegen_1._) `${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`) + .else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=oneOf.js.map + +/***/ }), + +/***/ 45333: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const code_1 = __webpack_require__(15765); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const util_2 = __webpack_require__(94227); +const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true))) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } + else { + gen.var(valid, true); // TODO var + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str, + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._) `${props}[${key}]`, true); + } + else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=patternProperties.js.map + +/***/ }), + +/***/ 65354: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const items_1 = __webpack_require__(20494); +const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items"), +}; +exports["default"] = def; +//# sourceMappingURL=prefixItems.js.map + +/***/ }), + +/***/ 40117: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const validate_1 = __webpack_require__(62586); +const code_1 = __webpack_require__(15765); +const util_1 = __webpack_require__(94227); +const additionalProperties_1 = __webpack_require__(38660); +const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, valid); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=properties.js.map + +/***/ }), + +/***/ 19713: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`, +}; +const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + }, +}; +exports["default"] = def; +//# sourceMappingURL=propertyNames.js.map + +/***/ }), + +/***/ 14426: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __webpack_require__(94227); +const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === undefined) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=thenElse.js.map + +/***/ }), + +/***/ 15765: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const names_1 = __webpack_require__(42023); +const util_2 = __webpack_require__(94227); +function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); + cxt.error(); + }); +} +exports.checkReportMissingProp = checkReportMissingProp; +function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); +} +exports.checkMissingProp = checkMissingProp; +function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); +} +exports.reportMissingProp = reportMissingProp; +function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, + }); +} +exports.hasPropFunc = hasPropFunc; +function isOwnProperty(gen, data, property) { + return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; +} +exports.isOwnProperty = isOwnProperty; +function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; +} +exports.propertyInData = propertyInData; +function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; +} +exports.noPropertyInData = noPropertyInData; +function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; +} +exports.allSchemaProperties = allSchemaProperties; +function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); +} +exports.schemaProperties = schemaProperties; +function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData], + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; +} +exports.callValidateCode = callValidateCode; +const newRegExp = (0, codegen_1._) `new RegExp`; +function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, + }); +} +exports.usePattern = usePattern; +function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num, + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } +} +exports.validateArray = validateArray; +function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true, + }, schValid); + gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); +} +exports.validateUnion = validateUnion; +//# sourceMappingURL=code.js.map + +/***/ }), + +/***/ 83463: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + }, +}; +exports["default"] = def; +//# sourceMappingURL=id.js.map + +/***/ }), + +/***/ 72128: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const id_1 = __webpack_require__(83463); +const ref_1 = __webpack_require__(13693); +const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default, +]; +exports["default"] = core; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 13693: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.callRef = exports.getValidate = void 0; +const ref_error_1 = __webpack_require__(34551); +const code_1 = __webpack_require__(15765); +const codegen_1 = __webpack_require__(99029); +const names_1 = __webpack_require__(42023); +const compile_1 = __webpack_require__(73835); +const util_1 = __webpack_require__(94227); +const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === undefined) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + }, +}; +function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate + ? gen.scopeValue("validate", { ref: sch.validate }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; +} +exports.getValidate = getValidate; +function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result + if (!allErrors) + gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._) `${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged + gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } + else { + const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } + else { + const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } +} +exports.callRef = callRef; +exports["default"] = def; +//# sourceMappingURL=ref.js.map + +/***/ }), + +/***/ 36653: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const types_1 = __webpack_require__(97652); +const compile_1 = __webpack_require__(73835); +const util_1 = __webpack_require__(94227); +const error = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +}; +const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch === null || sch === void 0 ? void 0 : sch.$ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) { + addMapping(sch.const, i); + } + else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i); + } + } + else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i; + } + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 97652: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DiscrError = void 0; +var DiscrError; +(function (DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; +})(DiscrError = exports.DiscrError || (exports.DiscrError = {})); +//# sourceMappingURL=types.js.map + +/***/ }), + +/***/ 86144: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core_1 = __webpack_require__(72128); +const validation_1 = __webpack_require__(67060); +const applicator_1 = __webpack_require__(56378); +const format_1 = __webpack_require__(97532); +const metadata_1 = __webpack_require__(69857); +const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, +]; +exports["default"] = draft7Vocabularies; +//# sourceMappingURL=draft7.js.map + +/***/ }), + +/***/ 94737: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`, +}; +const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }); + const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + // TODO simplify + gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._) `${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async + ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : (0, codegen_1._) `${format}(${data})`; + const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp + ? (0, codegen_1.regexpCode)(fmtDef) + : opts.code.formats + ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` + : undefined; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._) `await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`; + } + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=format.js.map + +/***/ }), + +/***/ 97532: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const format_1 = __webpack_require__(94737); +const format = [format_1.default]; +exports["default"] = format; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 69857: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.contentVocabulary = exports.metadataVocabulary = void 0; +exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +]; +exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +]; +//# sourceMappingURL=metadata.js.map + +/***/ }), + +/***/ 27935: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const equal_1 = __webpack_require__(76250); +const error = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`, +}; +const def = { + keyword: "const", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } + else { + cxt.fail((0, codegen_1._) `${schema} !== ${data}`); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=const.js.map + +/***/ }), + +/***/ 28643: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const equal_1 = __webpack_require__(76250); +const error = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, +}; +const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default))); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } + else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null + ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])` + : (0, codegen_1._) `${data} === ${sch}`; + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=enum.js.map + +/***/ }), + +/***/ 67060: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const limitNumber_1 = __webpack_require__(75882); +const multipleOf_1 = __webpack_require__(63439); +const limitLength_1 = __webpack_require__(77307); +const pattern_1 = __webpack_require__(90422); +const limitProperties_1 = __webpack_require__(34486); +const required_1 = __webpack_require__(34003); +const limitItems_1 = __webpack_require__(61163); +const uniqueItems_1 = __webpack_require__(60617); +const const_1 = __webpack_require__(27935); +const enum_1 = __webpack_require__(28643); +const validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default, +]; +exports["default"] = validation; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 61163: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=limitItems.js.map + +/***/ }), + +/***/ 77307: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const ucs2length_1 = __webpack_require__(53853); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=limitLength.js.map + +/***/ }), + +/***/ 75882: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const ops = codegen_1.operators; +const KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, +}; +const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, +}; +const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=limitNumber.js.map + +/***/ }), + +/***/ 34486: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, +}; +const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=limitProperties.js.map + +/***/ }), + +/***/ 63439: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const codegen_1 = __webpack_require__(99029); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`, +}; +const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec + ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : (0, codegen_1._) `${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=multipleOf.js.map + +/***/ }), + +/***/ 90422: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const code_1 = __webpack_require__(15765); +const codegen_1 = __webpack_require__(99029); +const error = { + message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, +}; +const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); + }, +}; +exports["default"] = def; +//# sourceMappingURL=pattern.js.map + +/***/ }), + +/***/ 34003: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const code_1 = __webpack_require__(15765); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const error = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`, +}; +const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } + else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } + else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=required.js.map + +/***/ }), + +/***/ 60617: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const dataType_1 = __webpack_require__(10208); +const codegen_1 = __webpack_require__(99029); +const util_1 = __webpack_require__(94227); +const equal_1 = __webpack_require__(76250); +const error = { + message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`, +}; +const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._) `${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i, j }); + gen.assign(valid, true); + gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._) `{}`); + gen.for((0, codegen_1._) `;${i}--;`, () => { + gen.let(item, (0, codegen_1._) `${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._) `continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`); + gen + .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._) `${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }) + .code((0, codegen_1._) `${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + }, +}; +exports["default"] = def; +//# sourceMappingURL=uniqueItems.js.map + +/***/ }), + +/***/ 87568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = exports; + +asn1.bignum = __webpack_require__(72344); + +asn1.define = (__webpack_require__(47363).define); +asn1.base = __webpack_require__(9673); +asn1.constants = __webpack_require__(22153); +asn1.decoders = __webpack_require__(22853); +asn1.encoders = __webpack_require__(24669); + + +/***/ }), + +/***/ 47363: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = __webpack_require__(87568); +var inherits = __webpack_require__(56698); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = (__webpack_require__(68961).runInThisContext)( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; + + +/***/ }), + +/***/ 47227: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); +var Reporter = (__webpack_require__(9673).Reporter); +var Buffer = (__webpack_require__(48287).Buffer); + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.t = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.d = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + + +/***/ }), + +/***/ 9673: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var base = exports; + +base.Reporter = (__webpack_require__(89220)/* .Reporter */ .a); +base.DecoderBuffer = (__webpack_require__(47227)/* .DecoderBuffer */ .t); +base.EncoderBuffer = (__webpack_require__(47227)/* .EncoderBuffer */ .d); +base.Node = __webpack_require__(90993); + + +/***/ }), + +/***/ 90993: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Reporter = (__webpack_require__(9673).Reporter); +var EncoderBuffer = (__webpack_require__(9673).EncoderBuffer); +var DecoderBuffer = (__webpack_require__(9673).DecoderBuffer); +var assert = __webpack_require__(43349); + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + var result = state['default']; + var present = true; + + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); + + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; + + +/***/ }), + +/***/ 89220: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.a = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; +}; + + +/***/ }), + +/***/ 74598: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = __webpack_require__(22153); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + + +/***/ }), + +/***/ 22153: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = __webpack_require__(74598); + + +/***/ }), + +/***/ 62010: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); + +var asn1 = __webpack_require__(87568); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + + +/***/ }), + +/***/ 22853: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var decoders = exports; + +decoders.der = __webpack_require__(62010); +decoders.pem = __webpack_require__(58903); + + +/***/ }), + +/***/ 58903: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); +var Buffer = (__webpack_require__(48287).Buffer); + +var DERDecoder = __webpack_require__(62010); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; + + +/***/ }), + +/***/ 70082: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); +var Buffer = (__webpack_require__(48287).Buffer); + +var asn1 = __webpack_require__(87568); +var base = asn1.base; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + + +/***/ }), + +/***/ 24669: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var encoders = exports; + +encoders.der = __webpack_require__(70082); +encoders.pem = __webpack_require__(90735); + + +/***/ }), + +/***/ 90735: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698); + +var DEREncoder = __webpack_require__(70082); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + + +/***/ }), + +/***/ 72344: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(78982).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 94148: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +/* provided dependency */ var console = __webpack_require__(96763); +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b + +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +var _require = __webpack_require__(69597), + _require$codes = _require.codes, + ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, + ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; +var AssertionError = __webpack_require__(3918); +var _require2 = __webpack_require__(40537), + inspect = _require2.inspect; +var _require$types = (__webpack_require__(40537).types), + isPromise = _require$types.isPromise, + isRegExp = _require$types.isRegExp; +var objectAssign = __webpack_require__(11514)(); +var objectIs = __webpack_require__(9394)(); +var RegExpPrototypeTest = __webpack_require__(38075)('RegExp.prototype.test'); +var errorCache = new Map(); +var isDeepEqual; +var isDeepStrictEqual; +var parseExpressionAt; +var findNodeAround; +var decoder; +function lazyLoadComparison() { + var comparison = __webpack_require__(82299); + isDeepEqual = comparison.isDeepEqual; + isDeepStrictEqual = comparison.isDeepStrictEqual; +} + +// Escape control characters but not \n and \t to keep the line breaks and +// indentation intact. +// eslint-disable-next-line no-control-regex +var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; +var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"])); +var escapeFn = function escapeFn(str) { + return meta[str.charCodeAt(0)]; +}; +var warned = false; + +// The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; +var NO_EXCEPTION_SENTINEL = {}; + +// All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function innerFail(obj) { + if (obj.message instanceof Error) throw obj.message; + throw new AssertionError(obj); +} +function fail(actual, expected, message, operator, stackStartFn) { + var argsLen = arguments.length; + var internalMessage; + if (argsLen === 0) { + internalMessage = 'Failed'; + } else if (argsLen === 1) { + message = actual; + actual = undefined; + } else { + if (warned === false) { + warned = true; + var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); + warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); + } + if (argsLen === 2) operator = '!='; + } + if (message instanceof Error) throw message; + var errArgs = { + actual: actual, + expected: expected, + operator: operator === undefined ? 'fail' : operator, + stackStartFn: stackStartFn || fail + }; + if (message !== undefined) { + errArgs.message = message; + } + var err = new AssertionError(errArgs); + if (internalMessage) { + err.message = internalMessage; + err.generatedMessage = true; + } + throw err; +} +assert.fail = fail; + +// The AssertionError is defined in internal/error. +assert.AssertionError = AssertionError; +function innerOk(fn, argLen, value, message) { + if (!value) { + var generatedMessage = false; + if (argLen === 0) { + generatedMessage = true; + message = 'No value argument passed to `assert.ok()`'; + } else if (message instanceof Error) { + throw message; + } + var err = new AssertionError({ + actual: value, + expected: true, + message: message, + operator: '==', + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} + +// Pure assertion tests whether a value is truthy, as determined +// by !!value. +function ok() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + innerOk.apply(void 0, [ok, args.length].concat(args)); +} +assert.ok = ok; + +// The equality assertion tests shallow, coercive equality with ==. +/* eslint-disable no-restricted-properties */ +assert.equal = function equal(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual != expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '==', + stackStartFn: equal + }); + } +}; + +// The non-equality assertion tests for whether two objects are not +// equal with !=. +assert.notEqual = function notEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual == expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '!=', + stackStartFn: notEqual + }); + } +}; + +// The equivalence assertion tests a deep equality relation. +assert.deepEqual = function deepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepEqual', + stackStartFn: deepEqual + }); + } +}; + +// The non-equivalence assertion tests for any deep inequality. +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepEqual', + stackStartFn: notDeepEqual + }); + } +}; +/* eslint-enable */ + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepStrictEqual', + stackStartFn: deepStrictEqual + }); + } +}; +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepStrictEqual', + stackStartFn: notDeepStrictEqual + }); + } +} +assert.strictEqual = function strictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (!objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'strictEqual', + stackStartFn: strictEqual + }); + } +}; +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notStrictEqual', + stackStartFn: notStrictEqual + }); + } +}; +var Comparison = /*#__PURE__*/_createClass(function Comparison(obj, keys, actual) { + var _this = this; + _classCallCheck(this, Comparison); + keys.forEach(function (key) { + if (key in obj) { + if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && RegExpPrototypeTest(obj[key], actual[key])) { + _this[key] = actual[key]; + } else { + _this[key] = obj[key]; + } + } + }); +}); +function compareExceptionKey(actual, expected, key, message, keys, fn) { + if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { + if (!message) { + // Create placeholder objects to create a nice output. + var a = new Comparison(actual, keys); + var b = new Comparison(expected, keys, actual); + var err = new AssertionError({ + actual: a, + expected: b, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.actual = actual; + err.expected = expected; + err.operator = fn.name; + throw err; + } + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: fn.name, + stackStartFn: fn + }); + } +} +function expectedException(actual, expected, msg, fn) { + if (typeof expected !== 'function') { + if (isRegExp(expected)) return RegExpPrototypeTest(expected, actual); + // assert.doesNotThrow does not accept objects. + if (arguments.length === 2) { + throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); + } + + // Handle primitives properly. + if (_typeof(actual) !== 'object' || actual === null) { + var err = new AssertionError({ + actual: actual, + expected: expected, + message: msg, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.operator = fn.name; + throw err; + } + var keys = Object.keys(expected); + // Special handle errors to make sure the name and the message are compared + // as well. + if (expected instanceof Error) { + keys.push('name', 'message'); + } else if (keys.length === 0) { + throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + keys.forEach(function (key) { + if (typeof actual[key] === 'string' && isRegExp(expected[key]) && RegExpPrototypeTest(expected[key], actual[key])) { + return; + } + compareExceptionKey(actual, expected, key, msg, keys, fn); + }); + return true; + } + // Guard instanceof against arrow functions as they don't have a prototype. + if (expected.prototype !== undefined && actual instanceof expected) { + return true; + } + if (Error.isPrototypeOf(expected)) { + return false; + } + return expected.call({}, actual) === true; +} +function getActual(fn) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); + } + try { + fn(); + } catch (e) { + return e; + } + return NO_EXCEPTION_SENTINEL; +} +function checkIsPromise(obj) { + // Accept native ES6 promises and promises that are implemented in a similar + // way. Do not accept thenables that use a function as `obj` and that have no + // `catch` handler. + + // TODO: thenables are checked up until they have the correct methods, + // but according to documentation, the `then` method should receive + // the `fulfill` and `reject` arguments as well or it may be never resolved. + + return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; +} +function waitForActual(promiseFn) { + return Promise.resolve().then(function () { + var resultPromise; + if (typeof promiseFn === 'function') { + // Return a rejected promise if `promiseFn` throws synchronously. + resultPromise = promiseFn(); + // Fail in case no promise is returned. + if (!checkIsPromise(resultPromise)) { + throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); + } + } else if (checkIsPromise(promiseFn)) { + resultPromise = promiseFn; + } else { + throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); + } + return Promise.resolve().then(function () { + return resultPromise; + }).then(function () { + return NO_EXCEPTION_SENTINEL; + }).catch(function (e) { + return e; + }); + }); +} +function expectsError(stackStartFn, actual, error, message) { + if (typeof error === 'string') { + if (arguments.length === 4) { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (_typeof(actual) === 'object' && actual !== null) { + if (actual.message === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); + } + } else if (actual === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); + } + message = error; + error = undefined; + } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (actual === NO_EXCEPTION_SENTINEL) { + var details = ''; + if (error && error.name) { + details += " (".concat(error.name, ")"); + } + details += message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; + innerFail({ + actual: undefined, + expected: error, + operator: stackStartFn.name, + message: "Missing expected ".concat(fnType).concat(details), + stackStartFn: stackStartFn + }); + } + if (error && !expectedException(actual, error, message, stackStartFn)) { + throw actual; + } +} +function expectsNoError(stackStartFn, actual, error, message) { + if (actual === NO_EXCEPTION_SENTINEL) return; + if (typeof error === 'string') { + message = error; + error = undefined; + } + if (!error || expectedException(actual, error)) { + var details = message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; + innerFail({ + actual: actual, + expected: error, + operator: stackStartFn.name, + message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), + stackStartFn: stackStartFn + }); + } + throw actual; +} +assert.throws = function throws(promiseFn) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); +}; +assert.rejects = function rejects(promiseFn) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return waitForActual(promiseFn).then(function (result) { + return expectsError.apply(void 0, [rejects, result].concat(args)); + }); +}; +assert.doesNotThrow = function doesNotThrow(fn) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); +}; +assert.doesNotReject = function doesNotReject(fn) { + for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + return waitForActual(fn).then(function (result) { + return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); + }); +}; +assert.ifError = function ifError(err) { + if (err !== null && err !== undefined) { + var message = 'ifError got unwanted exception: '; + if (_typeof(err) === 'object' && typeof err.message === 'string') { + if (err.message.length === 0 && err.constructor) { + message += err.constructor.name; + } else { + message += err.message; + } + } else { + message += inspect(err); + } + var newErr = new AssertionError({ + actual: err, + expected: null, + operator: 'ifError', + message: message, + stackStartFn: ifError + }); + + // Make sure we actually have a stack trace! + var origStack = err.stack; + if (typeof origStack === 'string') { + // This will remove any duplicated frames from the error frames taken + // from within `ifError` and add the original error frames to the newly + // created ones. + var tmp2 = origStack.split('\n'); + tmp2.shift(); + // Filter all frames existing in err.stack. + var tmp1 = newErr.stack.split('\n'); + for (var i = 0; i < tmp2.length; i++) { + // Find the first occurrence of the frame. + var pos = tmp1.indexOf(tmp2[i]); + if (pos !== -1) { + // Only keep new frames. + tmp1 = tmp1.slice(0, pos); + break; + } + } + newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); + } + throw newErr; + } +}; + +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a871df3dfb8ea663ef5e1f8f62701ec51384ecb +function internalMatch(string, regexp, message, fn, fnName) { + if (!isRegExp(regexp)) { + throw new ERR_INVALID_ARG_TYPE('regexp', 'RegExp', regexp); + } + var match = fnName === 'match'; + if (typeof string !== 'string' || RegExpPrototypeTest(regexp, string) !== match) { + if (message instanceof Error) { + throw message; + } + var generatedMessage = !message; + + // 'The input was expected to not match the regular expression ' + + message = message || (typeof string !== 'string' ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof(string), " (").concat(inspect(string), ")") : (match ? 'The input did not match the regular expression ' : 'The input was expected to not match the regular expression ') + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string), "\n")); + var err = new AssertionError({ + actual: string, + expected: regexp, + message: message, + operator: fnName, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +assert.match = function match(string, regexp, message) { + internalMatch(string, regexp, message, match, 'match'); +}; +assert.doesNotMatch = function doesNotMatch(string, regexp, message) { + internalMatch(string, regexp, message, doesNotMatch, 'doesNotMatch'); +}; + +// Expose a strict only variant of assert +function strict() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + innerOk.apply(void 0, [strict, args.length].concat(args)); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +/***/ }), + +/***/ 3918: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Currently in sync with Node.js lib/internal/assert/assertion_error.js +// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c + + + +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var _require = __webpack_require__(40537), + inspect = _require.inspect; +var _require2 = __webpack_require__(69597), + ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat +function repeat(str, count) { + count = Math.floor(count); + if (str.length == 0 || count == 0) return ''; + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; +} +var blue = ''; +var green = ''; +var red = ''; +var white = ''; +var kReadableOperator = { + deepStrictEqual: 'Expected values to be strictly deep-equal:', + strictEqual: 'Expected values to be strictly equal:', + strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', + deepEqual: 'Expected values to be loosely deep-equal:', + equal: 'Expected values to be loosely equal:', + notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', + notStrictEqual: 'Expected "actual" to be strictly unequal to:', + notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', + notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', + notEqual: 'Expected "actual" to be loosely unequal to:', + notIdentical: 'Values identical but not reference-equal:' +}; + +// Comparing short primitives should just show === / !== instead of using the +// diff. +var kMaxShortLength = 10; +function copyError(source) { + var keys = Object.keys(source); + var target = Object.create(Object.getPrototypeOf(source)); + keys.forEach(function (key) { + target[key] = source[key]; + }); + Object.defineProperty(target, 'message', { + value: source.message + }); + return target; +} +function inspectValue(val) { + // The util.inspect default values could be changed. This makes sure the + // error messages contain the necessary information nevertheless. + return inspect(val, { + compact: false, + customInspect: false, + depth: 1000, + maxArrayLength: Infinity, + // Assert compares only enumerable properties (with a few exceptions). + showHidden: false, + // Having a long line as error is better than wrapping the line for + // comparison for now. + // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we + // have meta information about the inspected properties (i.e., know where + // in what line the property starts and ends). + breakLength: Infinity, + // Assert does not detect proxies currently. + showProxy: false, + sorted: true, + // Inspect getters as we also check them when comparing entries. + getters: true + }); +} +function createErrDiff(actual, expected, operator) { + var other = ''; + var res = ''; + var lastPos = 0; + var end = ''; + var skipped = false; + var actualInspected = inspectValue(actual); + var actualLines = actualInspected.split('\n'); + var expectedLines = inspectValue(expected).split('\n'); + var i = 0; + var indicator = ''; + + // In case both values are objects explicitly mark them as not reference equal + // for the `strictEqual` operator. + if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { + operator = 'strictEqualObject'; + } + + // If "actual" and "expected" fit on a single line and they are not strictly + // equal, check further special handling. + if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { + var inputLength = actualLines[0].length + expectedLines[0].length; + // If the character length of "actual" and "expected" together is less than + // kMaxShortLength and if neither is an object and at least one of them is + // not `zero`, use the strict equal comparison to visualize the output. + if (inputLength <= kMaxShortLength) { + if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { + // -0 === +0 + return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); + } + } else if (operator !== 'strictEqualObject') { + // If the stderr is a tty and the input length is lower than the current + // columns per line, add a mismatch indicator below the output. If it is + // not a tty, use a default value of 80 characters. + var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; + if (inputLength < maxLength) { + while (actualLines[0][i] === expectedLines[0][i]) { + i++; + } + // Ignore the first characters. + if (i > 2) { + // Add position indicator for the first mismatch in case it is a + // single line and the input length is less than the column length. + indicator = "\n ".concat(repeat(' ', i), "^"); + i = 0; + } + } + } + } + + // Remove all ending lines that match (this optimizes the output for + // readability by reducing the number of total changed lines). + var a = actualLines[actualLines.length - 1]; + var b = expectedLines[expectedLines.length - 1]; + while (a === b) { + if (i++ < 2) { + end = "\n ".concat(a).concat(end); + } else { + other = a; + } + actualLines.pop(); + expectedLines.pop(); + if (actualLines.length === 0 || expectedLines.length === 0) break; + a = actualLines[actualLines.length - 1]; + b = expectedLines[expectedLines.length - 1]; + } + var maxLines = Math.max(actualLines.length, expectedLines.length); + // Strict equal with identical objects that are not identical by reference. + // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) + if (maxLines === 0) { + // We have to get the result again. The lines were all removed before. + var _actualLines = actualInspected.split('\n'); + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (_actualLines.length > 30) { + _actualLines[26] = "".concat(blue, "...").concat(white); + while (_actualLines.length > 27) { + _actualLines.pop(); + } + } + return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); + } + if (i > 3) { + end = "\n".concat(blue, "...").concat(white).concat(end); + skipped = true; + } + if (other !== '') { + end = "\n ".concat(other).concat(end); + other = ''; + } + var printedLines = 0; + var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); + var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); + for (i = 0; i < maxLines; i++) { + // Only extra expected lines exist + var cur = i - lastPos; + if (actualLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(expectedLines[i - 2]); + printedLines++; + } + res += "\n ".concat(expectedLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the expected line to the cache. + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); + printedLines++; + // Only extra actual lines exist + } else if (expectedLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); + printedLines++; + // Lines diverge + } else { + var expectedLine = expectedLines[i]; + var actualLine = actualLines[i]; + // If the lines diverge, specifically check for lines that only diverge by + // a trailing comma. In that case it is actually identical and we should + // mark it as such. + var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); + // If the expected line has a trailing comma but is otherwise identical, + // add a comma at the end of the actual line. Otherwise the output could + // look weird as in: + // + // [ + // 1 // No comma at the end! + // + 2 + // ] + // + if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { + divergingLines = false; + actualLine += ','; + } + if (divergingLines) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result and cache the expected diverging + // line so consecutive diverging lines show up as +++--- and not +-+-+-. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); + printedLines += 2; + // Lines are identical + } else { + // Add all cached information to the result before adding other things + // and reset the cache. + res += other; + other = ''; + // If the last diverging line is exactly one line above or if it is the + // very first line, add the line to the result. + if (cur === 1 || i === 0) { + res += "\n ".concat(actualLine); + printedLines++; + } + } + } + // Inspected object to big (Show ~20 rows max) + if (printedLines > 20 && i < maxLines - 2) { + return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); + } + } + return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); +} +var AssertionError = /*#__PURE__*/function (_Error, _inspect$custom) { + _inherits(AssertionError, _Error); + var _super = _createSuper(AssertionError); + function AssertionError(options) { + var _this; + _classCallCheck(this, AssertionError); + if (_typeof(options) !== 'object' || options === null) { + throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); + } + var message = options.message, + operator = options.operator, + stackStartFn = options.stackStartFn; + var actual = options.actual, + expected = options.expected; + var limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + if (message != null) { + _this = _super.call(this, String(message)); + } else { + if (process.stderr && process.stderr.isTTY) { + // Reset on each call to make sure we handle dynamically set environment + // variables correct. + if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { + blue = "\x1B[34m"; + green = "\x1B[32m"; + white = "\x1B[39m"; + red = "\x1B[31m"; + } else { + blue = ''; + green = ''; + white = ''; + red = ''; + } + } + // Prevent the error stack from being visible by duplicating the error + // in a very close way to the original in case both sides are actually + // instances of Error. + if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { + actual = copyError(actual); + expected = copyError(expected); + } + if (operator === 'deepStrictEqual' || operator === 'strictEqual') { + _this = _super.call(this, createErrDiff(actual, expected, operator)); + } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { + // In case the objects are equal but the operator requires unequal, show + // the first object and say A equals B + var base = kReadableOperator[operator]; + var res = inspectValue(actual).split('\n'); + + // In case "actual" is an object, it should not be reference equal. + if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { + base = kReadableOperator.notStrictEqualObject; + } + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (res.length > 30) { + res[26] = "".concat(blue, "...").concat(white); + while (res.length > 27) { + res.pop(); + } + } + + // Only print a single input. + if (res.length === 1) { + _this = _super.call(this, "".concat(base, " ").concat(res[0])); + } else { + _this = _super.call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")); + } + } else { + var _res = inspectValue(actual); + var other = ''; + var knownOperators = kReadableOperator[operator]; + if (operator === 'notDeepEqual' || operator === 'notEqual') { + _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); + if (_res.length > 1024) { + _res = "".concat(_res.slice(0, 1021), "..."); + } + } else { + other = "".concat(inspectValue(expected)); + if (_res.length > 512) { + _res = "".concat(_res.slice(0, 509), "..."); + } + if (other.length > 512) { + other = "".concat(other.slice(0, 509), "..."); + } + if (operator === 'deepEqual' || operator === 'equal') { + _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); + } else { + other = " ".concat(operator, " ").concat(other); + } + } + _this = _super.call(this, "".concat(_res).concat(other)); + } + } + Error.stackTraceLimit = limit; + _this.generatedMessage = !message; + Object.defineProperty(_assertThisInitialized(_this), 'name', { + value: 'AssertionError [ERR_ASSERTION]', + enumerable: false, + writable: true, + configurable: true + }); + _this.code = 'ERR_ASSERTION'; + _this.actual = actual; + _this.expected = expected; + _this.operator = operator; + if (Error.captureStackTrace) { + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); + } + // Create error message including the error code in the name. + _this.stack; + // Reset the name. + _this.name = 'AssertionError'; + return _possibleConstructorReturn(_this); + } + _createClass(AssertionError, [{ + key: "toString", + value: function toString() { + return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); + } + }, { + key: _inspect$custom, + value: function value(recurseTimes, ctx) { + // This limits the `actual` and `expected` property default inspection to + // the minimum depth. Otherwise those values would be too verbose compared + // to the actual error message which contains a combined view of these two + // input values. + return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, { + customInspect: false, + depth: 0 + })); + } + }]); + return AssertionError; +}( /*#__PURE__*/_wrapNativeSuper(Error), inspect.custom); +module.exports = AssertionError; + +/***/ }), + +/***/ 69597: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/errors.js +// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f + +/* eslint node-core/documented-errors: "error" */ +/* eslint node-core/alphabetize-errors: "error" */ +/* eslint node-core/prefer-util-format-errors: "error" */ + + + +// The whole point behind this internal module is to allow Node.js to no +// longer be forced to treat every error message change as a semver-major +// change. The NodeError classes here all expose a `code` property whose +// value statically and permanently identifies the error. While the error +// message may change, the code should not. +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var codes = {}; + +// Lazy loaded +var assert; +var util; +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /*#__PURE__*/function (_Base) { + _inherits(NodeError, _Base); + var _super = _createSuper(NodeError); + function NodeError(arg1, arg2, arg3) { + var _this; + _classCallCheck(this, NodeError); + _this = _super.call(this, getMessage(arg1, arg2, arg3)); + _this.code = code; + return _this; + } + return _createClass(NodeError); + }(Base); + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} +createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + if (assert === undefined) assert = __webpack_require__(94148); + assert(typeof name === 'string', "'name' must be a string"); + + // determiner: 'must be' or 'must not be' + var determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + var msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + // TODO(BridgeAR): Improve the output by showing `null` and similar. + msg += ". Received type ".concat(_typeof(actual)); + return msg; +}, TypeError); +createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { + var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; + if (util === undefined) util = __webpack_require__(40537); + var inspected = util.inspect(value); + if (inspected.length > 128) { + inspected = "".concat(inspected.slice(0, 128), "..."); + } + return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); +}, TypeError, RangeError); +createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { + var type; + if (value && value.constructor && value.constructor.name) { + type = "instance of ".concat(value.constructor.name); + } else { + type = "type ".concat(_typeof(value)); + } + return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); +}, TypeError); +createErrorType('ERR_MISSING_ARGS', function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (assert === undefined) assert = __webpack_require__(94148); + assert(args.length > 0, 'At least one arg needs to be specified'); + var msg = 'The '; + var len = args.length; + args = args.map(function (a) { + return "\"".concat(a, "\""); + }); + switch (len) { + case 1: + msg += "".concat(args[0], " argument"); + break; + case 2: + msg += "".concat(args[0], " and ").concat(args[1], " arguments"); + break; + default: + msg += args.slice(0, len - 1).join(', '); + msg += ", and ".concat(args[len - 1], " arguments"); + break; + } + return "".concat(msg, " must be specified"); +}, TypeError); +module.exports.codes = codes; + +/***/ }), + +/***/ 82299: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/comparisons.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var regexFlagsSupported = /a/g.flags !== undefined; +var arrayFromSet = function arrayFromSet(set) { + var array = []; + set.forEach(function (value) { + return array.push(value); + }); + return array; +}; +var arrayFromMap = function arrayFromMap(map) { + var array = []; + map.forEach(function (value, key) { + return array.push([key, value]); + }); + return array; +}; +var objectIs = Object.is ? Object.is : __webpack_require__(37653); +var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { + return []; +}; +var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(24133); +function uncurryThis(f) { + return f.call.bind(f); +} +var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); +var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); +var objectToString = uncurryThis(Object.prototype.toString); +var _require$types = (__webpack_require__(40537).types), + isAnyArrayBuffer = _require$types.isAnyArrayBuffer, + isArrayBufferView = _require$types.isArrayBufferView, + isDate = _require$types.isDate, + isMap = _require$types.isMap, + isRegExp = _require$types.isRegExp, + isSet = _require$types.isSet, + isNativeError = _require$types.isNativeError, + isBoxedPrimitive = _require$types.isBoxedPrimitive, + isNumberObject = _require$types.isNumberObject, + isStringObject = _require$types.isStringObject, + isBooleanObject = _require$types.isBooleanObject, + isBigIntObject = _require$types.isBigIntObject, + isSymbolObject = _require$types.isSymbolObject, + isFloat32Array = _require$types.isFloat32Array, + isFloat64Array = _require$types.isFloat64Array; +function isNonIndex(key) { + if (key.length === 0 || key.length > 10) return true; + for (var i = 0; i < key.length; i++) { + var code = key.charCodeAt(i); + if (code < 48 || code > 57) return true; + } + // The maximum size for an array is 2 ** 32 -1. + return key.length === 10 && key >= Math.pow(2, 32); +} +function getOwnNonIndexProperties(value) { + return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); +} + +// Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + var x = a.length; + var y = b.length; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +var ONLY_ENUMERABLE = undefined; +var kStrict = true; +var kLoose = false; +var kNoIterator = 0; +var kIsArray = 1; +var kIsSet = 2; +var kIsMap = 3; + +// Check if they have the same source and flags +function areSimilarRegExps(a, b) { + return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); +} +function areSimilarFloatArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (var offset = 0; offset < a.byteLength; offset++) { + if (a[offset] !== b[offset]) { + return false; + } + } + return true; +} +function areSimilarTypedArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; +} +function areEqualArrayBuffers(buf1, buf2) { + return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; +} +function isEqualBoxedPrimitive(val1, val2) { + if (isNumberObject(val1)) { + return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); + } + if (isStringObject(val1)) { + return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); + } + if (isBooleanObject(val1)) { + return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); + } + if (isBigIntObject(val1)) { + return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); + } + return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); +} + +// Notes: Type tags are historical [[Class]] properties that can be set by +// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS +// and retrieved using Object.prototype.toString.call(obj) in JS +// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring +// for a list of tags pre-defined in the spec. +// There are some unspecified tags in the wild too (e.g. typed array tags). +// Since tags can be altered, they only serve fast failures +// +// Typed arrays and buffers are checked by comparing the content in their +// underlying ArrayBuffer. This optimization requires that it's +// reasonable to interpret their underlying memory in the same way, +// which is checked by comparing their type tags. +// (e.g. a Uint8Array and a Uint16Array with the same memory content +// could still be different because they will be interpreted differently). +// +// For strict comparison, objects should have +// a) The same built-in type tags +// b) The same prototypes. + +function innerDeepEqual(val1, val2, strict, memos) { + // All identical values are equivalent, as determined by ===. + if (val1 === val2) { + if (val1 !== 0) return true; + return strict ? objectIs(val1, val2) : true; + } + + // Check more closely if val1 and val2 are equal. + if (strict) { + if (_typeof(val1) !== 'object') { + return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); + } + if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { + return false; + } + if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { + return false; + } + } else { + if (val1 === null || _typeof(val1) !== 'object') { + if (val2 === null || _typeof(val2) !== 'object') { + // eslint-disable-next-line eqeqeq + return val1 == val2; + } + return false; + } + if (val2 === null || _typeof(val2) !== 'object') { + return false; + } + } + var val1Tag = objectToString(val1); + var val2Tag = objectToString(val2); + if (val1Tag !== val2Tag) { + return false; + } + if (Array.isArray(val1)) { + // Check for sparse arrays and general fast path + if (val1.length !== val2.length) { + return false; + } + var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (keys1.length !== keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsArray, keys1); + } + // [browserify] This triggers on certain types in IE (Map/Set) so we don't + // wan't to early return out of the rest of the checks. However we can check + // if the second value is one of these values and the first isn't. + if (val1Tag === '[object Object]') { + // return keyCheck(val1, val2, strict, memos, kNoIterator); + if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { + return false; + } + } + if (isDate(val1)) { + if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { + return false; + } + } else if (isRegExp(val1)) { + if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { + return false; + } + } else if (isNativeError(val1) || val1 instanceof Error) { + // Do not compare the stack as it might differ even though the error itself + // is otherwise identical. + if (val1.message !== val2.message || val1.name !== val2.name) { + return false; + } + } else if (isArrayBufferView(val1)) { + if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { + if (!areSimilarFloatArrays(val1, val2)) { + return false; + } + } else if (!areSimilarTypedArrays(val1, val2)) { + return false; + } + // Buffer.compare returns true, so val1.length === val2.length. If they both + // only contain numeric keys, we don't need to exam further than checking + // the symbols. + var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (_keys.length !== _keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); + } else if (isSet(val1)) { + if (!isSet(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsSet); + } else if (isMap(val1)) { + if (!isMap(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsMap); + } else if (isAnyArrayBuffer(val1)) { + if (!areEqualArrayBuffers(val1, val2)) { + return false; + } + } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator); +} +function getEnumerables(val, keys) { + return keys.filter(function (k) { + return propertyIsEnumerable(val, k); + }); +} +function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { + // For all remaining Object pairs, including Array, objects and Maps, + // equivalence is determined by having: + // a) The same number of owned enumerable properties + // b) The same set of keys/indexes (although not necessarily the same order) + // c) Equivalent values for every corresponding key/index + // d) For Sets and Maps, equal contents + // Note: this accounts for both named and indexed properties on Arrays. + if (arguments.length === 5) { + aKeys = Object.keys(val1); + var bKeys = Object.keys(val2); + + // The pair must have the same number of owned properties. + if (aKeys.length !== bKeys.length) { + return false; + } + } + + // Cheap key test + var i = 0; + for (; i < aKeys.length; i++) { + if (!hasOwnProperty(val2, aKeys[i])) { + return false; + } + } + if (strict && arguments.length === 5) { + var symbolKeysA = objectGetOwnPropertySymbols(val1); + if (symbolKeysA.length !== 0) { + var count = 0; + for (i = 0; i < symbolKeysA.length; i++) { + var key = symbolKeysA[i]; + if (propertyIsEnumerable(val1, key)) { + if (!propertyIsEnumerable(val2, key)) { + return false; + } + aKeys.push(key); + count++; + } else if (propertyIsEnumerable(val2, key)) { + return false; + } + } + var symbolKeysB = objectGetOwnPropertySymbols(val2); + if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { + return false; + } + } else { + var _symbolKeysB = objectGetOwnPropertySymbols(val2); + if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { + return false; + } + } + } + if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { + return true; + } + + // Use memos to handle cycles. + if (memos === undefined) { + memos = { + val1: new Map(), + val2: new Map(), + position: 0 + }; + } else { + // We prevent up to two map.has(x) calls by directly retrieving the value + // and checking for undefined. The map can only contain numbers, so it is + // safe to check for undefined only. + var val2MemoA = memos.val1.get(val1); + if (val2MemoA !== undefined) { + var val2MemoB = memos.val2.get(val2); + if (val2MemoB !== undefined) { + return val2MemoA === val2MemoB; + } + } + memos.position++; + } + memos.val1.set(val1, memos.position); + memos.val2.set(val2, memos.position); + var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); + memos.val1.delete(val1); + memos.val2.delete(val2); + return areEq; +} +function setHasEqualElement(set, val1, strict, memo) { + // Go looking. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var val2 = setValues[i]; + if (innerDeepEqual(val1, val2, strict, memo)) { + // Remove the matching element to make sure we do not check that again. + set.delete(val2); + return true; + } + } + return false; +} + +// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using +// Sadly it is not possible to detect corresponding values properly in case the +// type is a string, number, bigint or boolean. The reason is that those values +// can match lots of different string values (e.g., 1n == '+00001'). +function findLooseMatchingPrimitives(prim) { + switch (_typeof(prim)) { + case 'undefined': + return null; + case 'object': + // Only pass in null as object! + return undefined; + case 'symbol': + return false; + case 'string': + prim = +prim; + // Loose equal entries exist only if the string is possible to convert to + // a regular number and not NaN. + // Fall through + case 'number': + if (numberIsNaN(prim)) { + return false; + } + } + return true; +} +function setMightHaveLoosePrim(a, b, prim) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) return altValue; + return b.has(altValue) && !a.has(altValue); +} +function mapMightHaveLoosePrim(a, b, prim, item, memo) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + var curB = b.get(altValue); + if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { + return false; + } + return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); +} +function setEquiv(a, b, strict, memo) { + // This is a lazily initiated Set of entries which have to be compared + // pairwise. + var set = null; + var aValues = arrayFromSet(a); + for (var i = 0; i < aValues.length; i++) { + var val = aValues[i]; + // Note: Checking for the objects first improves the performance for object + // heavy sets but it is a minor slow down for primitives. As they are fast + // to check this improves the worst case scenario instead. + if (_typeof(val) === 'object' && val !== null) { + if (set === null) { + set = new Set(); + } + // If the specified value doesn't exist in the second set its an not null + // object (or non strict only: a not matching primitive) we'll need to go + // hunting for something thats deep-(strict-)equal to it. To make this + // O(n log n) complexity we have to copy these values in a new set first. + set.add(val); + } else if (!b.has(val)) { + if (strict) return false; + + // Fast path to detect missing string, symbol, undefined and null values. + if (!setMightHaveLoosePrim(a, b, val)) { + return false; + } + if (set === null) { + set = new Set(); + } + set.add(val); + } + } + if (set !== null) { + var bValues = arrayFromSet(b); + for (var _i = 0; _i < bValues.length; _i++) { + var _val = bValues[_i]; + // We have to check if a primitive value is already + // matching and only if it's not, go hunting for it. + if (_typeof(_val) === 'object' && _val !== null) { + if (!setHasEqualElement(set, _val, strict, memo)) return false; + } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function mapHasEqualEntry(set, map, key1, item1, strict, memo) { + // To be able to handle cases like: + // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) + // ... we need to consider *all* matching keys, not just the first we find. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var key2 = setValues[i]; + if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { + set.delete(key2); + return true; + } + } + return false; +} +function mapEquiv(a, b, strict, memo) { + var set = null; + var aEntries = arrayFromMap(a); + for (var i = 0; i < aEntries.length; i++) { + var _aEntries$i = _slicedToArray(aEntries[i], 2), + key = _aEntries$i[0], + item1 = _aEntries$i[1]; + if (_typeof(key) === 'object' && key !== null) { + if (set === null) { + set = new Set(); + } + set.add(key); + } else { + // By directly retrieving the value we prevent another b.has(key) check in + // almost all possible cases. + var item2 = b.get(key); + if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { + if (strict) return false; + // Fast path to detect missing string, symbol, undefined and null + // keys. + if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; + if (set === null) { + set = new Set(); + } + set.add(key); + } + } + } + if (set !== null) { + var bEntries = arrayFromMap(b); + for (var _i2 = 0; _i2 < bEntries.length; _i2++) { + var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), + _key = _bEntries$_i[0], + item = _bEntries$_i[1]; + if (_typeof(_key) === 'object' && _key !== null) { + if (!mapHasEqualEntry(set, a, _key, item, strict, memo)) return false; + } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set, a, _key, item, false, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function objEquiv(a, b, strict, keys, memos, iterationType) { + // Sets and maps don't have their entries accessible via normal object + // properties. + var i = 0; + if (iterationType === kIsSet) { + if (!setEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsMap) { + if (!mapEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsArray) { + for (; i < a.length; i++) { + if (hasOwnProperty(a, i)) { + if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { + return false; + } + } else if (hasOwnProperty(b, i)) { + return false; + } else { + // Array is sparse. + var keysA = Object.keys(a); + for (; i < keysA.length; i++) { + var key = keysA[i]; + if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { + return false; + } + } + if (keysA.length !== Object.keys(b).length) { + return false; + } + return true; + } + } + } + + // The pair must have equivalent values for every corresponding key. + // Possibly expensive deep test: + for (i = 0; i < keys.length; i++) { + var _key2 = keys[i]; + if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) { + return false; + } + } + return true; +} +function isDeepEqual(val1, val2) { + return innerDeepEqual(val1, val2, kLoose); +} +function isDeepStrictEqual(val1, val2) { + return innerDeepEqual(val1, val2, kStrict); +} +module.exports = { + isDeepEqual: isDeepEqual, + isDeepStrictEqual: isDeepStrictEqual +}; + +/***/ }), + +/***/ 35682: +/***/ ((module, exports, __webpack_require__) => { + +const ascii = __webpack_require__(36209) +const base64 = __webpack_require__(10943) +const hex = __webpack_require__(51847) +const utf8 = __webpack_require__(86679) +const utf16le = __webpack_require__(65435) + +const LE = new Uint8Array(Uint16Array.of(0xff).buffer)[0] === 0xff + +function codecFor (encoding) { + switch (encoding) { + case 'ascii': + return ascii + case 'base64': + return base64 + case 'hex': + return hex + case 'utf8': + case 'utf-8': + case undefined: + return utf8 + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16le + default: + throw new Error(`Unknown encoding: ${encoding}`) + } +} + +function isBuffer (value) { + return value instanceof Uint8Array +} + +function isEncoding (encoding) { + try { + codecFor(encoding) + return true + } catch { + return false + } +} + +function alloc (size, fill, encoding) { + const buffer = new Uint8Array(size) + if (fill !== undefined) exports.fill(buffer, fill, 0, buffer.byteLength, encoding) + return buffer +} + +function allocUnsafe (size) { + return new Uint8Array(size) +} + +function allocUnsafeSlow (size) { + return new Uint8Array(size) +} + +function byteLength (string, encoding) { + return codecFor(encoding).byteLength(string) +} + +function compare (a, b) { + if (a === b) return 0 + + const len = Math.min(a.byteLength, b.byteLength) + + a = new DataView(a.buffer, a.byteOffset, a.byteLength) + b = new DataView(b.buffer, b.byteOffset, b.byteLength) + + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + const x = a.getUint32(i, LE) + const y = b.getUint32(i, LE) + if (x !== y) break + } + + for (; i < len; i++) { + const x = a.getUint8(i) + const y = b.getUint8(i) + if (x < y) return -1 + if (x > y) return 1 + } + + return a.byteLength > b.byteLength ? 1 : a.byteLength < b.byteLength ? -1 : 0 +} + +function concat (buffers, totalLength) { + if (totalLength === undefined) { + totalLength = buffers.reduce((len, buffer) => len + buffer.byteLength, 0) + } + + const result = new Uint8Array(totalLength) + + let offset = 0 + for (const buffer of buffers) { + if (offset + buffer.byteLength > result.byteLength) { + const sub = buffer.subarray(0, result.byteLength - offset) + result.set(sub, offset) + return result + } + result.set(buffer, offset) + offset += buffer.byteLength + } + + return result +} + +function copy (source, target, targetStart = 0, start = 0, end = source.byteLength) { + if (end > 0 && end < start) return 0 + if (end === start) return 0 + if (source.byteLength === 0 || target.byteLength === 0) return 0 + + if (targetStart < 0) throw new RangeError('targetStart is out of range') + if (start < 0 || start >= source.byteLength) throw new RangeError('sourceStart is out of range') + if (end < 0) throw new RangeError('sourceEnd is out of range') + + if (targetStart >= target.byteLength) targetStart = target.byteLength + if (end > source.byteLength) end = source.byteLength + if (target.byteLength - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (source === target) { + target.copyWithin(targetStart, start, end) + } else { + target.set(source.subarray(start, end), targetStart) + } + + return len +} + +function equals (a, b) { + if (a === b) return true + if (a.byteLength !== b.byteLength) return false + + const len = a.byteLength + + a = new DataView(a.buffer, a.byteOffset, a.byteLength) + b = new DataView(b.buffer, b.byteOffset, b.byteLength) + + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + if (a.getUint32(i, LE) !== b.getUint32(i, LE)) return false + } + + for (; i < len; i++) { + if (a.getUint8(i) !== b.getUint8(i)) return false + } + + return true +} + +function fill (buffer, value, offset, end, encoding) { + if (typeof value === 'string') { + // fill(buffer, string, encoding) + if (typeof offset === 'string') { + encoding = offset + offset = 0 + end = buffer.byteLength + + // fill(buffer, string, offset, encoding) + } else if (typeof end === 'string') { + encoding = end + end = buffer.byteLength + } + } else if (typeof value === 'number') { + value = value & 0xff + } else if (typeof value === 'boolean') { + value = +value + } + + if (offset < 0 || buffer.byteLength < offset || buffer.byteLength < end) { + throw new RangeError('Out of range index') + } + + if (offset === undefined) offset = 0 + if (end === undefined) end = buffer.byteLength + + if (end <= offset) return buffer + + if (!value) value = 0 + + if (typeof value === 'number') { + for (let i = offset; i < end; ++i) { + buffer[i] = value + } + } else { + value = isBuffer(value) ? value : from(value, encoding) + + const len = value.byteLength + + for (let i = 0; i < end - offset; ++i) { + buffer[i + offset] = value[i % len] + } + } + + return buffer +} + +function from (value, encodingOrOffset, length) { + // from(string, encoding) + if (typeof value === 'string') return fromString(value, encodingOrOffset) + + // from(array) + if (Array.isArray(value)) return fromArray(value) + + // from(buffer) + if (ArrayBuffer.isView(value)) return fromBuffer(value) + + // from(arrayBuffer[, byteOffset[, length]]) + return fromArrayBuffer(value, encodingOrOffset, length) +} + +function fromString (string, encoding) { + const codec = codecFor(encoding) + const buffer = new Uint8Array(codec.byteLength(string)) + codec.write(buffer, string, 0, buffer.byteLength) + return buffer +} + +function fromArray (array) { + const buffer = new Uint8Array(array.length) + buffer.set(array) + return buffer +} + +function fromBuffer (buffer) { + const copy = new Uint8Array(buffer.byteLength) + copy.set(buffer) + return copy +} + +function fromArrayBuffer (arrayBuffer, byteOffset, length) { + return new Uint8Array(arrayBuffer, byteOffset, length) +} + +function includes (buffer, value, byteOffset, encoding) { + return indexOf(buffer, value, byteOffset, encoding) !== -1 +} + +function bidirectionalIndexOf (buffer, value, byteOffset, encoding, first) { + if (buffer.byteLength === 0) return -1 + + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset === undefined) { + byteOffset = first ? 0 : (buffer.length - 1) + } else if (byteOffset < 0) { + byteOffset += buffer.byteLength + } + + if (byteOffset >= buffer.byteLength) { + if (first) return -1 + else byteOffset = buffer.byteLength - 1 + } else if (byteOffset < 0) { + if (first) byteOffset = 0 + else return -1 + } + + if (typeof value === 'string') { + value = from(value, encoding) + } else if (typeof value === 'number') { + value = value & 0xff + + if (first) { + return buffer.indexOf(value, byteOffset) + } else { + return buffer.lastIndexOf(value, byteOffset) + } + } + + if (value.byteLength === 0) return -1 + + if (first) { + let foundIndex = -1 + + for (let i = byteOffset; i < buffer.byteLength; i++) { + if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === value.byteLength) return foundIndex + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + value.byteLength > buffer.byteLength) { + byteOffset = buffer.byteLength - value.byteLength + } + + for (let i = byteOffset; i >= 0; i--) { + let found = true + + for (let j = 0; j < value.byteLength; j++) { + if (buffer[i + j] !== value[j]) { + found = false + break + } + } + + if (found) return i + } + } + + return -1 +} + +function indexOf (buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, true /* first */) +} + +function lastIndexOf (buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, false /* last */) +} + +function swap (buffer, n, m) { + const i = buffer[n] + buffer[n] = buffer[m] + buffer[m] = i +} + +function swap16 (buffer) { + const len = buffer.byteLength + + if (len % 2 !== 0) throw new RangeError('Buffer size must be a multiple of 16-bits') + + for (let i = 0; i < len; i += 2) swap(buffer, i, i + 1) + + return buffer +} + +function swap32 (buffer) { + const len = buffer.byteLength + + if (len % 4 !== 0) throw new RangeError('Buffer size must be a multiple of 32-bits') + + for (let i = 0; i < len; i += 4) { + swap(buffer, i, i + 3) + swap(buffer, i + 1, i + 2) + } + + return buffer +} + +function swap64 (buffer) { + const len = buffer.byteLength + + if (len % 8 !== 0) throw new RangeError('Buffer size must be a multiple of 64-bits') + + for (let i = 0; i < len; i += 8) { + swap(buffer, i, i + 7) + swap(buffer, i + 1, i + 6) + swap(buffer, i + 2, i + 5) + swap(buffer, i + 3, i + 4) + } + + return buffer +} + +function toBuffer (buffer) { + return buffer +} + +function toString (buffer, encoding, start = 0, end = buffer.byteLength) { + const len = buffer.byteLength + + if (start >= len) return '' + if (end <= start) return '' + if (start < 0) start = 0 + if (end > len) end = len + + if (start !== 0 || end < len) buffer = buffer.subarray(start, end) + + return codecFor(encoding).toString(buffer) +} + +function write (buffer, string, offset, length, encoding) { + // write(buffer, string) + if (offset === undefined) { + encoding = 'utf8' + + // write(buffer, string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + + // write(buffer, string, offset, encoding) + } else if (encoding === undefined && typeof length === 'string') { + encoding = length + length = undefined + } + + return codecFor(encoding).write(buffer, string, offset, length) +} + +function writeDoubleLE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat64(offset, value, true) + + return offset + 8 +} + +function writeFloatLE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat32(offset, value, true) + + return offset + 4 +} + +function writeUInt32LE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setUint32(offset, value, true) + + return offset + 4 +} + +function writeInt32LE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setInt32(offset, value, true) + + return offset + 4 +} + +function readDoubleLE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getFloat64(offset, true) +} + +function readFloatLE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getFloat32(offset, true) +} + +function readUInt32LE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getUint32(offset, true) +} + +function readInt32LE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getInt32(offset, true) +} + +module.exports = exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE +} + + +/***/ }), + +/***/ 36209: +/***/ ((module) => { + +function byteLength (string) { + return string.length +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i++) { + result += String.fromCharCode(buffer[i]) + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0; i < len; i++) { + buffer[offset + i] = string.charCodeAt(i) + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 10943: +/***/ ((module) => { + +const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +const codes = new Uint8Array(256) + +for (let i = 0; i < alphabet.length; i++) { + codes[alphabet.charCodeAt(i)] = i +} + +codes[/* - */ 0x2d] = 62 +codes[/* _ */ 0x5f] = 63 + +function byteLength (string) { + let len = string.length + + if (string.charCodeAt(len - 1) === 0x3d) len-- + if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len-- + + return (len * 3) >>> 2 +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i += 3) { + result += ( + alphabet[buffer[i] >> 2] + + alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] + + alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] + + alphabet[buffer[i + 2] & 63] + ) + } + + if (len % 3 === 2) { + result = result.substring(0, result.length - 1) + '=' + } else if (len % 3 === 1) { + result = result.substring(0, result.length - 2) + '==' + } + + return result +}; + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0, j = 0; j < len; i += 4) { + const a = codes[string.charCodeAt(i)] + const b = codes[string.charCodeAt(i + 1)] + const c = codes[string.charCodeAt(i + 2)] + const d = codes[string.charCodeAt(i + 3)] + + buffer[j++] = (a << 2) | (b >> 4) + buffer[j++] = ((b & 15) << 4) | (c >> 2) + buffer[j++] = ((c & 3) << 6) | (d & 63) + } + + return len +}; + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 51847: +/***/ ((module) => { + +function byteLength (string) { + return string.length >>> 1 +} + +function toString (buffer) { + const len = buffer.byteLength + + buffer = new DataView(buffer.buffer, buffer.byteOffset, len) + + let result = '' + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + result += buffer.getUint32(i).toString(16).padStart(8, '0') + } + + for (; i < len; i++) { + result += buffer.getUint8(i).toString(16).padStart(2, '0') + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0; i < len; i++) { + const a = hexValue(string.charCodeAt(i * 2)) + const b = hexValue(string.charCodeAt(i * 2 + 1)) + + if (a === undefined || b === undefined) { + return buffer.subarray(0, i) + } + + buffer[offset + i] = (a << 4) | b + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + +function hexValue (char) { + if (char >= 0x30 && char <= 0x39) return char - 0x30 + if (char >= 0x41 && char <= 0x46) return char - 0x41 + 10 + if (char >= 0x61 && char <= 0x66) return char - 0x61 + 10 +} + + +/***/ }), + +/***/ 65435: +/***/ ((module) => { + +function byteLength (string) { + return string.length * 2 +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len - 1; i += 2) { + result += String.fromCharCode(buffer[i] + (buffer[i + 1] * 256)) + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + let units = len + + for (let i = 0; i < string.length; ++i) { + if ((units -= 2) < 0) break + + const c = string.charCodeAt(i) + const hi = c >> 8 + const lo = c % 256 + + buffer[offset + i * 2] = lo + buffer[offset + i * 2 + 1] = hi + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 86679: +/***/ ((module) => { + +function byteLength (string) { + let length = 0 + + for (let i = 0, n = string.length; i < n; i++) { + const code = string.charCodeAt(i) + + if (code >= 0xd800 && code <= 0xdbff && i + 1 < n) { + const code = string.charCodeAt(i + 1) + + if (code >= 0xdc00 && code <= 0xdfff) { + length += 4 + i++ + continue + } + } + + if (code <= 0x7f) length += 1 + else if (code <= 0x7ff) length += 2 + else length += 3 + } + + return length +} + +let toString + +if (typeof TextDecoder !== 'undefined') { + const decoder = new TextDecoder() + + toString = function toString (buffer) { + return decoder.decode(buffer) + } +} else { + toString = function toString (buffer) { + const len = buffer.byteLength + + let output = '' + let i = 0 + + while (i < len) { + let byte = buffer[i] + + if (byte <= 0x7f) { + output += String.fromCharCode(byte) + i++ + continue + } + + let bytesNeeded = 0 + let codePoint = 0 + + if (byte <= 0xdf) { + bytesNeeded = 1 + codePoint = byte & 0x1f + } else if (byte <= 0xef) { + bytesNeeded = 2 + codePoint = byte & 0x0f + } else if (byte <= 0xf4) { + bytesNeeded = 3 + codePoint = byte & 0x07 + } + + if (len - i - bytesNeeded > 0) { + let k = 0 + + while (k < bytesNeeded) { + byte = buffer[i + k + 1] + codePoint = (codePoint << 6) | (byte & 0x3f) + k += 1 + } + } else { + codePoint = 0xfffd + bytesNeeded = len - i + } + + output += String.fromCodePoint(codePoint) + i += bytesNeeded + 1 + } + + return output + } +} + +let write + +if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder() + + write = function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + encoder.encodeInto(string, buffer.subarray(offset, offset + len)) + return len + } +} else { + write = function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + buffer = buffer.subarray(offset, offset + len) + + let i = 0 + let j = 0 + + while (i < string.length) { + const code = string.codePointAt(i) + + if (code <= 0x7f) { + buffer[j++] = code + i++ + continue + } + + let count = 0 + let bits = 0 + + if (code <= 0x7ff) { + count = 6 + bits = 0xc0 + } else if (code <= 0xffff) { + count = 12 + bits = 0xe0 + } else if (code <= 0x1fffff) { + count = 18 + bits = 0xf0 + } + + buffer[j++] = bits | (code >> count) + count -= 6 + + while (count >= 0) { + buffer[j++] = 0x80 | ((code >> count) & 0x3f) + count -= 6 + } + + i += code >= 0x10000 ? 2 : 1 + } + + return len + } +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 67526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 92096: +/***/ ((module, exports, __webpack_require__) => { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + } + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + } + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + } + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + } + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + } + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + } + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + } + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + } + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + } + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + } + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + } + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + } + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + } + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, t, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + } + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + } + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + } + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + } + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; +})(); + +// Node.js check +if ( true && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +//amd check +if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return bigInt; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); +} + + +/***/ }), + +/***/ 60654: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(85702)(__webpack_require__(86989)) + + +/***/ }), + +/***/ 4315: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +const Transform = (__webpack_require__(28399).Transform) + +module.exports = class Blake extends Transform { + constructor (engine, options) { + super(options) + + this._engine = engine + this._finalized = false + } + + _transform (chunk, encoding, callback) { + let error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + _flush (callback) { + let error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + update (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._engine.update(data) + + return this + } + + digest (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + let digest = this._engine.digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + return digest + } +} + + +/***/ }), + +/***/ 85702: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Blake = __webpack_require__(4315) + +module.exports = (engines) => { + const getEngine = (algorithm) => { + const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm + switch (hash) { + case 'blake224': return engines.Blake224 + case 'blake256': return engines.Blake256 + case 'blake384': return engines.Blake384 + case 'blake512': return engines.Blake512 + + default: throw new Error('Invald algorithm: ' + algorithm) + } + } + + return (algorithm, options) => { + const Engine = getEngine(algorithm) + return new Blake(new Engine(), options) + } +} + + +/***/ }), + +/***/ 34588: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +class Blake { + _lengthCarry (arr) { + for (let j = 0; j < arr.length; ++j) { + if (arr[j] < 0x0100000000) break + arr[j] -= 0x0100000000 + arr[j + 1] += 1 + } + } + + update (data) { + const block = this._block + let offset = 0 + + while (this._blockOffset + data.length - offset >= block.length) { + for (let i = this._blockOffset; i < block.length;) block[i++] = data[offset++] + + this._length[0] += block.length * 8 + this._lengthCarry(this._length) + + this._compress() + this._blockOffset = 0 + } + + while (offset < data.length) block[this._blockOffset++] = data[offset++] + } +} + +Blake.sigma = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], + [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], + [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], + [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], + [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], + [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], + [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], + [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], + [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], + [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], + [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], + [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], + [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9] +] + +Blake.u256 = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917 +] + +Blake.u512 = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, + 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69 +] + +Blake.padding = Buffer.from([ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +]) + +module.exports = Blake + + +/***/ }), + +/***/ 48746: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +const Blake256 = __webpack_require__(23287) + +const zo = Buffer.from([0x00]) +const oo = Buffer.from([0x80]) + +module.exports = class Blake224 extends Blake256 { + constructor () { + super() + + this._h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ] + + this._zo = zo + this._oo = oo + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(28) + for (let i = 0; i < 7; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 23287: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +const Blake = __webpack_require__(34588) + +const zo = Buffer.from([0x01]) +const oo = Buffer.from([0x81]) + +const rot = (x, n) => ((x << (32 - n)) | (x >>> n)) >>> 0 + +function g (v, m, i, a, b, c, d, e) { + const sigma = Blake.sigma + const u256 = Blake.u256 + + v[a] = (v[a] + ((m[sigma[i][e]] ^ u256[sigma[i][e + 1]]) >>> 0) + v[b]) >>> 0 + v[d] = rot(v[d] ^ v[a], 16) + v[c] = (v[c] + v[d]) >>> 0 + v[b] = rot(v[b] ^ v[c], 12) + v[a] = (v[a] + ((m[sigma[i][e + 1]] ^ u256[sigma[i][e]]) >>> 0) + v[b]) >>> 0 + v[d] = rot(v[d] ^ v[a], 8) + v[c] = (v[c] + v[d]) >>> 0 + v[b] = rot(v[b] ^ v[c], 7) +} + +module.exports = class Blake256 extends Blake { + constructor () { + super() + + this._h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ] + + this._s = [0, 0, 0, 0] + + this._block = Buffer.alloc(64) + this._blockOffset = 0 + this._length = [0, 0] + + this._nullt = false + + this._zo = zo + this._oo = oo + } + + _compress () { + const u256 = Blake.u256 + const v = new Array(16) + const m = new Array(16) + let i + + for (i = 0; i < 16; ++i) m[i] = this._block.readUInt32BE(i * 4) + for (i = 0; i < 8; ++i) v[i] = this._h[i] >>> 0 + for (i = 8; i < 12; ++i) v[i] = (this._s[i - 8] ^ u256[i - 8]) >>> 0 + for (i = 12; i < 16; ++i) v[i] = u256[i - 8] + + if (!this._nullt) { + v[12] = (v[12] ^ this._length[0]) >>> 0 + v[13] = (v[13] ^ this._length[0]) >>> 0 + v[14] = (v[14] ^ this._length[1]) >>> 0 + v[15] = (v[15] ^ this._length[1]) >>> 0 + } + + for (i = 0; i < 14; ++i) { + /* column step */ + g(v, m, i, 0, 4, 8, 12, 0) + g(v, m, i, 1, 5, 9, 13, 2) + g(v, m, i, 2, 6, 10, 14, 4) + g(v, m, i, 3, 7, 11, 15, 6) + /* diagonal step */ + g(v, m, i, 0, 5, 10, 15, 8) + g(v, m, i, 1, 6, 11, 12, 10) + g(v, m, i, 2, 7, 8, 13, 12) + g(v, m, i, 3, 4, 9, 14, 14) + } + + for (i = 0; i < 16; ++i) this._h[i % 8] = (this._h[i % 8] ^ v[i]) >>> 0 + for (i = 0; i < 8; ++i) this._h[i] = (this._h[i] ^ this._s[i % 4]) >>> 0 + } + + _padding () { + let lo = this._length[0] + this._blockOffset * 8 + let hi = this._length[1] + if (lo >= 0x0100000000) { + lo -= 0x0100000000 + hi += 1 + } + + const msglen = Buffer.alloc(8) + msglen.writeUInt32BE(hi, 0) + msglen.writeUInt32BE(lo, 4) + + if (this._blockOffset === 55) { + this._length[0] -= 8 + this.update(this._oo) + } else { + if (this._blockOffset < 55) { + if (this._blockOffset === 0) this._nullt = true + this._length[0] -= (55 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 55 - this._blockOffset)) + } else { + this._length[0] -= (64 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 64 - this._blockOffset)) + this._length[0] -= 55 * 8 + this.update(Blake.padding.slice(1, 1 + 55)) + this._nullt = true + } + + this.update(this._zo) + this._length[0] -= 8 + } + + this._length[0] -= 64 + this.update(msglen) + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(32) + for (let i = 0; i < 8; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 399: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +const Blake512 = __webpack_require__(61070) + +const zo = Buffer.from([0x00]) +const oo = Buffer.from([0x80]) + +module.exports = class Blake384 extends Blake512 { + constructor () { + super() + + this._h = [ + 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 + ] + + this._zo = zo + this._oo = oo + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(48) + for (let i = 0; i < 12; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 61070: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +const Blake = __webpack_require__(34588) + +const zo = Buffer.from([0x01]) +const oo = Buffer.from([0x81]) + +function rot (v, i, j, n) { + let hi = v[i * 2] ^ v[j * 2] + let lo = v[i * 2 + 1] ^ v[j * 2 + 1] + + if (n >= 32) { + lo = lo ^ hi + hi = lo ^ hi + lo = lo ^ hi + n -= 32 + } + + if (n === 0) { + v[i * 2] = hi >>> 0 + v[i * 2 + 1] = lo >>> 0 + } else { + v[i * 2] = ((hi >>> n) | (lo << (32 - n))) >>> 0 + v[i * 2 + 1] = ((lo >>> n) | (hi << (32 - n))) >>> 0 + } +} + +function g (v, m, i, a, b, c, d, e) { + const sigma = Blake.sigma + const u512 = Blake.u512 + let lo + + // v[a] += (m[sigma[i][e]] ^ u512[sigma[i][e+1]]) + v[b]; + lo = v[a * 2 + 1] + ((m[sigma[i][e] * 2 + 1] ^ u512[sigma[i][e + 1] * 2 + 1]) >>> 0) + v[b * 2 + 1] + v[a * 2] = (v[a * 2] + ((m[sigma[i][e] * 2] ^ u512[sigma[i][e + 1] * 2]) >>> 0) + v[b * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[a * 2 + 1] = lo >>> 0 + + // v[d] = ROT( v[d] ^ v[a],32); + rot(v, d, a, 32) + + // v[c] += v[d]; + lo = v[c * 2 + 1] + v[d * 2 + 1] + v[c * 2] = (v[c * 2] + v[d * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[c * 2 + 1] = lo >>> 0 + + // v[b] = ROT( v[b] ^ v[c],25); + rot(v, b, c, 25) + + // v[a] += (m[sigma[i][e+1]] ^ u512[sigma[i][e]])+v[b]; + lo = v[a * 2 + 1] + ((m[sigma[i][e + 1] * 2 + 1] ^ u512[sigma[i][e] * 2 + 1]) >>> 0) + v[b * 2 + 1] + v[a * 2] = (v[a * 2] + ((m[sigma[i][e + 1] * 2] ^ u512[sigma[i][e] * 2]) >>> 0) + v[b * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[a * 2 + 1] = lo >>> 0 + + // v[d] = ROT( v[d] ^ v[a],16); + rot(v, d, a, 16) + + // v[c] += v[d]; + lo = v[c * 2 + 1] + v[d * 2 + 1] + v[c * 2] = (v[c * 2] + v[d * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[c * 2 + 1] = lo >>> 0 + + // v[b] = ROT( v[b] ^ v[c],11) + rot(v, b, c, 11) +} + +module.exports = class Blake512 extends Blake { + constructor () { + super() + + this._h = [ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 + ] + + this._s = [0, 0, 0, 0, 0, 0, 0, 0] + + this._block = Buffer.alloc(128) + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._nullt = false + + this._zo = zo + this._oo = oo + } + + _compress () { + const u512 = Blake.u512 + const v = new Array(32) + const m = new Array(32) + let i + + for (i = 0; i < 32; ++i) m[i] = this._block.readUInt32BE(i * 4) + for (i = 0; i < 16; ++i) v[i] = this._h[i] >>> 0 + for (i = 16; i < 24; ++i) v[i] = (this._s[i - 16] ^ u512[i - 16]) >>> 0 + for (i = 24; i < 32; ++i) v[i] = u512[i - 16] + + if (!this._nullt) { + v[24] = (v[24] ^ this._length[1]) >>> 0 + v[25] = (v[25] ^ this._length[0]) >>> 0 + v[26] = (v[26] ^ this._length[1]) >>> 0 + v[27] = (v[27] ^ this._length[0]) >>> 0 + v[28] = (v[28] ^ this._length[3]) >>> 0 + v[29] = (v[29] ^ this._length[2]) >>> 0 + v[30] = (v[30] ^ this._length[3]) >>> 0 + v[31] = (v[31] ^ this._length[2]) >>> 0 + } + + for (i = 0; i < 16; ++i) { + /* column step */ + g(v, m, i, 0, 4, 8, 12, 0) + g(v, m, i, 1, 5, 9, 13, 2) + g(v, m, i, 2, 6, 10, 14, 4) + g(v, m, i, 3, 7, 11, 15, 6) + /* diagonal step */ + g(v, m, i, 0, 5, 10, 15, 8) + g(v, m, i, 1, 6, 11, 12, 10) + g(v, m, i, 2, 7, 8, 13, 12) + g(v, m, i, 3, 4, 9, 14, 14) + } + + for (i = 0; i < 16; ++i) { + this._h[(i % 8) * 2] = (this._h[(i % 8) * 2] ^ v[i * 2]) >>> 0 + this._h[(i % 8) * 2 + 1] = (this._h[(i % 8) * 2 + 1] ^ v[i * 2 + 1]) >>> 0 + } + + for (i = 0; i < 8; ++i) { + this._h[i * 2] = (this._h[i * 2] ^ this._s[(i % 4) * 2]) >>> 0 + this._h[i * 2 + 1] = (this._h[i * 2 + 1] ^ this._s[(i % 4) * 2 + 1]) >>> 0 + } + } + + _padding () { + const len = this._length.slice() + len[0] += this._blockOffset * 8 + this._lengthCarry(len) + + const msglen = Buffer.alloc(16) + for (let i = 0; i < 4; ++i) msglen.writeUInt32BE(len[3 - i], i * 4) + + if (this._blockOffset === 111) { + this._length[0] -= 8 + this.update(this._oo) + } else { + if (this._blockOffset < 111) { + if (this._blockOffset === 0) this._nullt = true + this._length[0] -= (111 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 111 - this._blockOffset)) + } else { + this._length[0] -= (128 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 128 - this._blockOffset)) + this._length[0] -= 111 * 8 + this.update(Blake.padding.slice(1, 1 + 111)) + this._nullt = true + } + + this.update(this._zo) + this._length[0] -= 8 + } + + this._length[0] -= 128 + this.update(msglen) + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(64) + for (let i = 0; i < 16; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 86989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = { + Blake224: __webpack_require__(48746), + Blake256: __webpack_require__(23287), + Blake384: __webpack_require__(399), + Blake512: __webpack_require__(61070) +} + + +/***/ }), + +/***/ 91892: +/***/ ((module) => { + +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __toBinary = /* @__PURE__ */ (() => { + var table = new Uint8Array(128); + for (var i = 0; i < 64; i++) + table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i; + return (base64) => { + var n = base64.length, bytes2 = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0); + for (var i2 = 0, j = 0; i2 < n; ) { + var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)]; + var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)]; + bytes2[j++] = c0 << 2 | c1 >> 4; + bytes2[j++] = c1 << 4 | c2 >> 2; + bytes2[j++] = c2 << 6 | c3; + } + return bytes2; + }; +})(); + +// wasm-binary:./blake2b.wat +var require_blake2b = __commonJS({ + "wasm-binary:./blake2b.wat"(exports2, module2) { + module2.exports = __toBinary("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs="); + } +}); + +// wasm-module:./blake2b.wat +var bytes = require_blake2b(); +var compiled = WebAssembly.compile(bytes); +module.exports = async (imports) => { + const instance = await WebAssembly.instantiate(await compiled, imports); + return instance.exports; +}; + + +/***/ }), + +/***/ 51685: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var assert = __webpack_require__(86889) +var b4a = __webpack_require__(35682) + +var wasm = null +var wasmPromise = typeof WebAssembly !== "undefined" && __webpack_require__(91892)().then(mod => { + wasm = mod +}) + +var head = 64 +var freeList = [] + +module.exports = Blake2b +var BYTES_MIN = module.exports.BYTES_MIN = 16 +var BYTES_MAX = module.exports.BYTES_MAX = 64 +var BYTES = module.exports.BYTES = 32 +var KEYBYTES_MIN = module.exports.KEYBYTES_MIN = 16 +var KEYBYTES_MAX = module.exports.KEYBYTES_MAX = 64 +var KEYBYTES = module.exports.KEYBYTES = 32 +var SALTBYTES = module.exports.SALTBYTES = 16 +var PERSONALBYTES = module.exports.PERSONALBYTES = 16 + +function Blake2b (digestLength, key, salt, personal, noAssert) { + if (!(this instanceof Blake2b)) return new Blake2b(digestLength, key, salt, personal, noAssert) + if (!wasm) throw new Error('WASM not loaded. Wait for Blake2b.ready(cb)') + if (!digestLength) digestLength = 32 + + if (noAssert !== true) { + assert(digestLength >= BYTES_MIN, 'digestLength must be at least ' + BYTES_MIN + ', was given ' + digestLength) + assert(digestLength <= BYTES_MAX, 'digestLength must be at most ' + BYTES_MAX + ', was given ' + digestLength) + if (key != null) { + assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer') + assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length) + assert(key.length <= KEYBYTES_MAX, 'key must be at least ' + KEYBYTES_MAX + ', was given ' + key.length) + } + if (salt != null) { + assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer') + assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length) + } + if (personal != null) { + assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer') + assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length) + } + } + + if (!freeList.length) { + freeList.push(head) + head += 216 + } + + this.digestLength = digestLength + this.finalized = false + this.pointer = freeList.pop() + this._memory = new Uint8Array(wasm.memory.buffer) + + this._memory.fill(0, 0, 64) + this._memory[0] = this.digestLength + this._memory[1] = key ? key.length : 0 + this._memory[2] = 1 // fanout + this._memory[3] = 1 // depth + + if (salt) this._memory.set(salt, 32) + if (personal) this._memory.set(personal, 48) + + if (this.pointer + 216 > this._memory.length) this._realloc(this.pointer + 216) // we need 216 bytes for the state + wasm.blake2b_init(this.pointer, this.digestLength) + + if (key) { + this.update(key) + this._memory.fill(0, head, head + key.length) // whiteout key + this._memory[this.pointer + 200] = 128 + } +} + +Blake2b.prototype._realloc = function (size) { + wasm.memory.grow(Math.max(0, Math.ceil(Math.abs(size - this._memory.length) / 65536))) + this._memory = new Uint8Array(wasm.memory.buffer) +} + +Blake2b.prototype.update = function (input) { + assert(this.finalized === false, 'Hash instance finalized') + assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer') + + if (head + input.length > this._memory.length) this._realloc(head + input.length) + this._memory.set(input, head) + wasm.blake2b_update(this.pointer, head, head + input.length) + return this +} + +Blake2b.prototype.digest = function (enc) { + assert(this.finalized === false, 'Hash instance finalized') + this.finalized = true + + freeList.push(this.pointer) + wasm.blake2b_final(this.pointer) + + if (!enc || enc === 'binary') { + return this._memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength) + } + + if (typeof enc === 'string') { + return b4a.toString(this._memory, enc, this.pointer + 128, this.pointer + 128 + this.digestLength) + } + + assert(enc instanceof Uint8Array && enc.length >= this.digestLength, 'input must be Uint8Array or Buffer') + for (var i = 0; i < this.digestLength; i++) { + enc[i] = this._memory[this.pointer + 128 + i] + } + + return enc +} + +// libsodium compat +Blake2b.prototype.final = Blake2b.prototype.digest + +Blake2b.WASM = wasm +Blake2b.SUPPORTED = typeof WebAssembly !== 'undefined' + +Blake2b.ready = function (cb) { + if (!cb) cb = noop + if (!wasmPromise) return cb(new Error('WebAssembly not supported')) + return wasmPromise.then(() => cb(), cb) +} + +Blake2b.prototype.ready = Blake2b.ready + +Blake2b.prototype.getPartialHash = function () { + return this._memory.slice(this.pointer, this.pointer + 216); +} + +Blake2b.prototype.setPartialHash = function (ph) { + this._memory.set(ph, this.pointer); +} + +function noop () {} + + +/***/ }), + +/***/ 72206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var assert = __webpack_require__(86889) +var b2wasm = __webpack_require__(51685) + +// 64-bit unsigned addition +// Sets v[a,a+1] += v[b,b+1] +// v should be a Uint32Array +function ADD64AA (v, a, b) { + var o0 = v[a] + v[b] + var o1 = v[a + 1] + v[b + 1] + if (o0 >= 0x100000000) { + o1++ + } + v[a] = o0 + v[a + 1] = o1 +} + +// 64-bit unsigned addition +// Sets v[a,a+1] += b +// b0 is the low 32 bits of b, b1 represents the high 32 bits +function ADD64AC (v, a, b0, b1) { + var o0 = v[a] + b0 + if (b0 < 0) { + o0 += 0x100000000 + } + var o1 = v[a + 1] + b1 + if (o0 >= 0x100000000) { + o1++ + } + v[a] = o0 + v[a + 1] = o1 +} + +// Little-endian byte access +function B2B_GET32 (arr, i) { + return (arr[i] ^ + (arr[i + 1] << 8) ^ + (arr[i + 2] << 16) ^ + (arr[i + 3] << 24)) +} + +// G Mixing function +// The ROTRs are inlined for speed +function B2B_G (a, b, c, d, ix, iy) { + var x0 = m[ix] + var x1 = m[ix + 1] + var y0 = m[iy] + var y1 = m[iy + 1] + + ADD64AA(v, a, b) // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s + ADD64AC(v, a, x0, x1) // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + var xor0 = v[d] ^ v[a] + var xor1 = v[d + 1] ^ v[a + 1] + v[d] = xor1 + v[d + 1] = xor0 + + ADD64AA(v, c, d) + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c] + xor1 = v[b + 1] ^ v[c + 1] + v[b] = (xor0 >>> 24) ^ (xor1 << 8) + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8) + + ADD64AA(v, a, b) + ADD64AC(v, a, y0, y1) + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a] + xor1 = v[d + 1] ^ v[a + 1] + v[d] = (xor0 >>> 16) ^ (xor1 << 16) + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16) + + ADD64AA(v, c, d) + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c] + xor1 = v[b + 1] ^ v[c + 1] + v[b] = (xor1 >>> 31) ^ (xor0 << 1) + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1) +} + +// Initialization Vector +var BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]) + +var SIGMA8 = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +] + +// These are offsets into a uint64 buffer. +// Multiply them all by 2 to make them offsets into a uint32 buffer, +// because this is Javascript and we don't have uint64s +var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 })) + +// Compression function. 'last' flag indicates last block. +// Note we're representing 16 uint64s as 32 uint32s +var v = new Uint32Array(32) +var m = new Uint32Array(32) +function blake2bCompress (ctx, last) { + var i = 0 + + // init work variables + for (i = 0; i < 16; i++) { + v[i] = ctx.h[i] + v[i + 16] = BLAKE2B_IV32[i] + } + + // low 64 bits of offset + v[24] = v[24] ^ ctx.t + v[25] = v[25] ^ (ctx.t / 0x100000000) + // high 64 bits not supported, offset may not be higher than 2**53-1 + + // last block flag set ? + if (last) { + v[28] = ~v[28] + v[29] = ~v[29] + } + + // get little-endian words + for (i = 0; i < 32; i++) { + m[i] = B2B_GET32(ctx.b, 4 * i) + } + + // twelve rounds of mixing + for (i = 0; i < 12; i++) { + B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]) + B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]) + B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]) + B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]) + B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]) + B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]) + B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]) + B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]) + } + + for (i = 0; i < 16; i++) { + ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16] + } +} + +// reusable parameter_block +var parameter_block = new Uint8Array([ + 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth + 0, 0, 0, 0, // 4: leaf length, sequential mode + 0, 0, 0, 0, // 8: node offset + 0, 0, 0, 0, // 12: node offset + 0, 0, 0, 0, // 16: node depth, inner length, rfu + 0, 0, 0, 0, // 20: rfu + 0, 0, 0, 0, // 24: rfu + 0, 0, 0, 0, // 28: rfu + 0, 0, 0, 0, // 32: salt + 0, 0, 0, 0, // 36: salt + 0, 0, 0, 0, // 40: salt + 0, 0, 0, 0, // 44: salt + 0, 0, 0, 0, // 48: personal + 0, 0, 0, 0, // 52: personal + 0, 0, 0, 0, // 56: personal + 0, 0, 0, 0 // 60: personal +]) + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +function Blake2b (outlen, key, salt, personal) { + // zero out parameter_block before usage + parameter_block.fill(0) + // state, 'param block' + + this.b = new Uint8Array(128) + this.h = new Uint32Array(16) + this.t = 0 // input count + this.c = 0 // pointer within buffer + this.outlen = outlen // output length in bytes + + parameter_block[0] = outlen + if (key) parameter_block[1] = key.length + parameter_block[2] = 1 // fanout + parameter_block[3] = 1 // depth + + if (salt) parameter_block.set(salt, 32) + if (personal) parameter_block.set(personal, 48) + + // initialize hash state + for (var i = 0; i < 16; i++) { + this.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameter_block, i * 4) + } + + // key the hash, if applicable + if (key) { + blake2bUpdate(this, key) + // at the end + this.c = 128 + } +} + +Blake2b.prototype.update = function (input) { + assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer') + blake2bUpdate(this, input) + return this +} + +Blake2b.prototype.digest = function (out) { + var buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out + assert(buf instanceof Uint8Array, 'out must be "binary", "hex", Uint8Array, or Buffer') + assert(buf.length >= this.outlen, 'out must have at least outlen bytes of space') + blake2bFinal(this, buf) + if (out === 'hex') return hexSlice(buf) + return buf +} + +Blake2b.prototype.final = Blake2b.prototype.digest + +Blake2b.ready = function (cb) { + b2wasm.ready(function () { + cb() // ignore the error + }) +} + +// Updates a BLAKE2b streaming hash +// Requires hash context and Uint8Array (byte array) +function blake2bUpdate (ctx, input) { + for (var i = 0; i < input.length; i++) { + if (ctx.c === 128) { // buffer full ? + ctx.t += ctx.c // add counters + blake2bCompress(ctx, false) // compress (not last) + ctx.c = 0 // counter to zero + } + ctx.b[ctx.c++] = input[i] + } +} + +// Completes a BLAKE2b streaming hash +// Returns a Uint8Array containing the message digest +function blake2bFinal (ctx, out) { + ctx.t += ctx.c // mark last block offset + + while (ctx.c < 128) { // fill up with zeros + ctx.b[ctx.c++] = 0 + } + blake2bCompress(ctx, true) // final block flag = 1 + + for (var i = 0; i < ctx.outlen; i++) { + out[i] = ctx.h[i >> 2] >> (8 * (i & 3)) + } + return out +} + +function hexSlice (buf) { + var str = '' + for (var i = 0; i < buf.length; i++) str += toHex(buf[i]) + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +var Proto = Blake2b + +module.exports = function createHash (outlen, key, salt, personal, noAssert) { + if (noAssert !== true) { + assert(outlen >= BYTES_MIN, 'outlen must be at least ' + BYTES_MIN + ', was given ' + outlen) + assert(outlen <= BYTES_MAX, 'outlen must be at most ' + BYTES_MAX + ', was given ' + outlen) + if (key != null) { + assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer') + assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length) + assert(key.length <= KEYBYTES_MAX, 'key must be at most ' + KEYBYTES_MAX + ', was given ' + key.length) + } + if (salt != null) { + assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer') + assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length) + } + if (personal != null) { + assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer') + assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length) + } + } + + return new Proto(outlen, key, salt, personal) +} + +module.exports.ready = function (cb) { + b2wasm.ready(function () { // ignore errors + cb() + }) +} + +module.exports.WASM_SUPPORTED = b2wasm.SUPPORTED +module.exports.WASM_LOADED = false + +var BYTES_MIN = module.exports.BYTES_MIN = 16 +var BYTES_MAX = module.exports.BYTES_MAX = 64 +var BYTES = module.exports.BYTES = 32 +var KEYBYTES_MIN = module.exports.KEYBYTES_MIN = 16 +var KEYBYTES_MAX = module.exports.KEYBYTES_MAX = 64 +var KEYBYTES = module.exports.KEYBYTES = 32 +var SALTBYTES = module.exports.SALTBYTES = 16 +var PERSONALBYTES = module.exports.PERSONALBYTES = 16 + +b2wasm.ready(function (err) { + if (!err) { + module.exports.WASM_LOADED = true + module.exports = b2wasm + } +}) + + +/***/ }), + +/***/ 65403: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var bloom = __webpack_require__(40710); +module.exports = bloom; + +/***/ }), + +/***/ 88217: +/***/ ((module) => { + +/** +* A simple bitview for Array buffer. +* @author: Joy Ghosh. +* @version: 0.0.1 +*/ + +var BitView = function(buffer){ + this.buffer = buffer; + this.unit8 = new Uint8Array(this.buffer); +} + +/** +* Returns the bit value at position 'index'. +*/ +BitView.prototype.get = function(index){ + var value = this.unit8[index >> 3]; + var offset = index & 0x7; + return ((value >> (7-offset)) & 1); +} + +/** +* Sets the bit value at specified position 'index'. +*/ +BitView.prototype.set = function(index){ + var offset = index & 0x7; + this.unit8[index >> 3] |= (0x80 >> offset); +} + +/** +* Clears the bit at position 'index'. +*/ +BitView.prototype.clear = function(index){ + var offset = index & 0x7; + this.unit8[index >> 3] &= ~(0x80 >> offset); +} + +/** +* Returns the byte length of this array buffer. +*/ +BitView.prototype.length = function(){ + return this.unit8.byteLength; +} + +/** +* Returns the array buffer. +*/ +BitView.prototype.view = function(){ + return this.unit8; +} + +module.exports = BitView; + + +/***/ }), + +/***/ 40710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** +* Bloom filter. +* @author: Joy Ghosh +* @version: 0.0.1 +*/ + +var BitView = __webpack_require__(88217); +var fnv_1a = __webpack_require__(89897); +var one_at_a_time_hash = __webpack_require__(81397); + +//Constants. +const BITS_IN_BYTE = 8; +const FALSE_POSITIVE_TOLERANCE = 0.000001; + +/** +* Bloom filter object. +* n represents number of elements in this filter. +*/ +var BloomFilter = function(n, false_postive_tolerance = FALSE_POSITIVE_TOLERANCE){ + //Bits in Bloom filter. + this.m = Math.ceil((-2)*n*Math.log(false_postive_tolerance)); + //Number of hash functions. + this.k = Math.ceil(0.7*(this.m/n)); + + //Normalize size. + this.size = (this.m > BITS_IN_BYTE) ? (Math.ceil(this.m/BITS_IN_BYTE)) : 1; //default size is a byte. + + //Initialize bit array for filter. + this.bitview = new BitView(new ArrayBuffer(this.size)); +} + +//Generate hash value. +BloomFilter.prototype.calculateHash = function(x,m,i){ + //Double hash technique. + return ((fnv_1a(x) + (i*one_at_a_time_hash(x)))%m); +} + +//Looks for membership. +BloomFilter.prototype.test = function(data){ + var hash = data; + for(var i=0; i { + +/** +Fowler-Noll-Vo hash function. +@author: Joy Ghosh +@version: 0.0.1 +*/ + +//FNV constants. +const FNV_PRIME = 16777619; +const FNV_OFFSET_BASIS = 2166136261; + +/** +FNV hash function. (32-bit version) +FNV step 1: hash = hash XOR byte_of_data. +FNV step 2: hash = hash * FNV_Prime. +*/ +function fnv_1a(value){ + + var hash = FNV_OFFSET_BASIS; + for(var i=0; i>> 0; +} + +//FNV step 1:hash = hash XOR byte_of_data. +function fnv_xor(hash, byte_of_data){ + return (hash ^ byte_of_data); +} + +//FNV step 2: hash = hash * FNV_Prime. +function fnv_multiply(hash){ + hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); + return hash; +} + +module.exports = fnv_1a; + +/***/ }), + +/***/ 81397: +/***/ ((module) => { + +/** +Jenkins one_at_a_time hash function. +@author: Joy Ghosh +@version: 0.0.1 +*/ + +/** +* Jenkins's one at a time hash function. +*/ +function one_at_a_time_hash(key){ + + var hash = 0; + for(var i=0;i> 6); + } + + hash += (hash << 3); + hash = hash ^ (hash >> 11); + hash += (hash << 15); + return hash; +} + +module.exports = one_at_a_time_hash; + +/***/ }), + +/***/ 39404: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(47790).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this._strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // '0' - '9' + if (c >= 48 && c <= 57) { + return c - 48; + // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this._strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + b = c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; + + // '0' - '9' + } else { + b = c; + } + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this._strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + function move (dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } + + BN.prototype._move = function _move (dest) { + move(dest, this); + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype._strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility + if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { + try { + BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; + } + } else { + BN.prototype.inspect = inspect; + } + + function inspect () { + return (this.red ? ''; + } + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16, 2); + }; + + if (Buffer) { + BN.prototype.toBuffer = function toBuffer (endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + var allocate = function allocate (ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; + }; + + BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { + var position = 0; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = (word >> 8) & 0xff; + } + if (position < res.length) { + res[position++] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position < res.length) { + res[position++] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position < res.length) { + res[position++] = carry; + + while (position < res.length) { + res[position++] = 0; + } + } + }; + + BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { + var position = res.length - 1; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position--] = word & 0xff; + if (position >= 0) { + res[position--] = (word >> 8) & 0xff; + } + if (position >= 0) { + res[position--] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position >= 0) { + res[position--] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position >= 0) { + res[position--] = carry; + + while (position >= 0) { + res[position--] = 0; + } + } + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] >>> wbit) & 0x01; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this._strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this._strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this._strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this._strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this._strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this._strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out._strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out._strip(); + } + + function jumboMulTo (self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out._strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this._strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this._strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this._strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this._strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this._strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this._strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modrn = function modrn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return isNegNum ? -acc : acc; + }; + + // WARNING: DEPRECATED + BN.prototype.modn = function modn (num) { + return this.modrn(num); + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + this._strip(); + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this._strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 15037: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + +if (typeof self === 'object') { + if (self.crypto && self.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker with no crypto support + try { + var crypto = __webpack_require__(73776); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } +} + + +/***/ }), + +/***/ 50462: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var Buffer = (__webpack_require__(92861).Buffer) + +function asUInt32Array (buf) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + + var len = (buf.length / 4) | 0 + var out = new Array(len) + + for (var i = 0; i < len; i++) { + out[i] = buf.readUInt32BE(i * 4) + } + + return out +} + +function scrubVec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } +} + +function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { + var SUB_MIX0 = SUB_MIX[0] + var SUB_MIX1 = SUB_MIX[1] + var SUB_MIX2 = SUB_MIX[2] + var SUB_MIX3 = SUB_MIX[3] + + var s0 = M[0] ^ keySchedule[0] + var s1 = M[1] ^ keySchedule[1] + var s2 = M[2] ^ keySchedule[2] + var s3 = M[3] ^ keySchedule[3] + var t0, t1, t2, t3 + var ksRow = 4 + + for (var round = 1; round < nRounds; round++) { + t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + t1 = t1 >>> 0 + t2 = t2 >>> 0 + t3 = t3 >>> 0 + + return [t0, t1, t2, t3] +} + +// AES constants +var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +var G = (function () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + d[j] = (j << 1) ^ 0x11b + } + } + + var SBOX = [] + var INV_SBOX = [] + var SUB_MIX = [[], [], [], []] + var INV_SUB_MIX = [[], [], [], []] + + // Walk GF(2^8) + var x = 0 + var xi = 0 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + SBOX[x] = sx + INV_SBOX[sx] = x + + // Compute multiplication + var x2 = d[x] + var x4 = d[x2] + var x8 = d[x4] + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100) + SUB_MIX[0][x] = (t << 24) | (t >>> 8) + SUB_MIX[1][x] = (t << 16) | (t >>> 16) + SUB_MIX[2][x] = (t << 8) | (t >>> 24) + SUB_MIX[3][x] = t + + // Compute inv sub bytes, inv mix columns tables + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + INV_SUB_MIX[3][sx] = t + + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + INV_SUB_MIX: INV_SUB_MIX + } +})() + +function AES (key) { + this._key = asUInt32Array(key) + this._reset() +} + +AES.blockSize = 4 * 4 +AES.keySize = 256 / 8 +AES.prototype.blockSize = AES.blockSize +AES.prototype.keySize = AES.keySize +AES.prototype._reset = function () { + var keyWords = this._key + var keySize = keyWords.length + var nRounds = keySize + 6 + var ksRows = (nRounds + 1) * 4 + + var keySchedule = [] + for (var k = 0; k < keySize; k++) { + keySchedule[k] = keyWords[k] + } + + for (k = keySize; k < ksRows; k++) { + var t = keySchedule[k - 1] + + if (k % keySize === 0) { + t = (t << 8) | (t >>> 24) + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + + t ^= RCON[(k / keySize) | 0] << 24 + } else if (keySize > 6 && k % keySize === 4) { + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + } + + keySchedule[k] = keySchedule[k - keySize] ^ t + } + + var invKeySchedule = [] + for (var ik = 0; ik < ksRows; ik++) { + var ksR = ksRows - ik + var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] + + if (ik < 4 || ksR <= 4) { + invKeySchedule[ik] = tt + } else { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] + } + } + + this._nRounds = nRounds + this._keySchedule = keySchedule + this._invKeySchedule = invKeySchedule +} + +AES.prototype.encryptBlockRaw = function (M) { + M = asUInt32Array(M) + return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) +} + +AES.prototype.encryptBlock = function (M) { + var out = this.encryptBlockRaw(M) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = asUInt32Array(M) + + // swap + var m1 = M[1] + M[1] = M[3] + M[3] = m1 + + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrubVec(this._keySchedule) + scrubVec(this._invKeySchedule) + scrubVec(this._key) +} + +module.exports.AES = AES + + +/***/ }), + +/***/ 92356: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var aes = __webpack_require__(50462) +var Buffer = (__webpack_require__(92861).Buffer) +var Transform = __webpack_require__(56168) +var inherits = __webpack_require__(56698) +var GHASH = __webpack_require__(25892) +var xor = __webpack_require__(30295) +var incr32 = __webpack_require__(45122) + +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) out++ + + var len = Math.min(a.length, b.length) + for (var i = 0; i < len; ++i) { + out += (a[i] ^ b[i]) + } + + return out +} + +function calcIv (self, iv, ck) { + if (iv.length === 12) { + self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) + } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out +} +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + var h = Buffer.alloc(4, 0) + + this._cipher = new aes.AES(key) + var ck = this._cipher.encryptBlock(h) + this._ghash = new GHASH(ck) + iv = calcIv(this, iv, ck) + + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + this._mode = mode + + this._authTag = null + this._called = false +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) + } + } + + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} + +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') + + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') + + this._authTag = tag + this._cipher.scrub() +} + +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') + + return this._authTag +} + +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') + + this._authTag = tag +} + +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (this._called) throw new Error('Attempting to set AAD in unsupported state') + + this._ghash.update(buf) + this._alen += buf.length +} + +module.exports = StreamCipher + + +/***/ }), + +/***/ 1241: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ciphers = __webpack_require__(25799) +var deciphers = __webpack_require__(36171) +var modes = __webpack_require__(3219) + +function getCiphers () { + return Object.keys(modes) +} + +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + + +/***/ }), + +/***/ 36171: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var AuthCipher = __webpack_require__(92356) +var Buffer = (__webpack_require__(92861).Buffer) +var MODES = __webpack_require__(530) +var StreamCipher = __webpack_require__(50650) +var Transform = __webpack_require__(56168) +var aes = __webpack_require__(50462) +var ebtk = __webpack_require__(68078) +var inherits = __webpack_require__(56698) + +function Decipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Decipher, Transform) + +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} + +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} + +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + + return null +} + +Splitter.prototype.flush = function () { + if (this.cache.length) return this.cache +} + +function unpad (last) { + var padded = last[15] + if (padded < 1 || padded > 16) { + throw new Error('unable to decrypt data') + } + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) return + + return last.slice(0, 16 - padded) +} + +function createDecipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv, true) + } + + return new Decipher(config.module, password, iv) +} + +function createDecipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} + +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv + + +/***/ }), + +/***/ 25799: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var MODES = __webpack_require__(530) +var AuthCipher = __webpack_require__(92356) +var Buffer = (__webpack_require__(92861).Buffer) +var StreamCipher = __webpack_require__(50650) +var Transform = __webpack_require__(56168) +var aes = __webpack_require__(50462) +var ebtk = __webpack_require__(68078) +var inherits = __webpack_require__(56698) + +function Cipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Cipher, Transform) + +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + + return Buffer.concat(out) +} + +var PADDING = Buffer.alloc(16, 0x10) + +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } + + if (!chunk.equals(PADDING)) { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} + +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} + +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = Buffer.allocUnsafe(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + + return Buffer.concat([this.cache, padBuff]) +} + +function createCipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv) + } + + return new Cipher(config.module, password, iv) +} + +function createCipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher + + +/***/ }), + +/***/ 25892: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) +var ZEROES = Buffer.alloc(16, 0) + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} + +function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + buf.writeUInt32BE(out[3] >>> 0, 12) + return buf +} + +function GHASH (key) { + this.h = key + this.state = Buffer.alloc(16, 0) + this.cache = Buffer.allocUnsafe(0) +} + +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsbVi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + Zi[2] ^= Vi[2] + Zi[3] ^= Vi[3] + } + + // Store the value of LSB(V_i) + lsbVi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsbVi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} + +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} + +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, ZEROES], 16)) + } + + this.ghash(fromArray([0, abl, 0, bl])) + return this.state +} + +module.exports = GHASH + + +/***/ }), + +/***/ 45122: +/***/ ((module) => { + +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} +module.exports = incr32 + + +/***/ }), + +/***/ 92884: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var xor = __webpack_require__(30295) + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} + + +/***/ }), + +/***/ 46383: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) +var xor = __webpack_require__(30295) + +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} + +exports.encrypt = function (self, data, decrypt) { + var out = Buffer.allocUnsafe(0) + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = Buffer.allocUnsafe(0) + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} + + +/***/ }), + +/***/ 55264: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) + +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} + +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = Buffer.allocUnsafe(buffer.length) + buffer = Buffer.concat([buffer, Buffer.from([value])]) + + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + + +/***/ }), + +/***/ 86975: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) + +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + + self._prev = Buffer.concat([ + self._prev.slice(1), + Buffer.from([decrypt ? byteParam : out]) + ]) + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + + +/***/ }), + +/***/ 63053: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var xor = __webpack_require__(30295) +var Buffer = (__webpack_require__(92861).Buffer) +var incr32 = __webpack_require__(45122) + +function getBlock (self) { + var out = self._cipher.encryptBlockRaw(self._prev) + incr32(self._prev) + return out +} + +var blockSize = 16 +exports.encrypt = function (self, chunk) { + var chunkNum = Math.ceil(chunk.length / blockSize) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + + +/***/ }), + +/***/ 52632: +/***/ ((__unused_webpack_module, exports) => { + +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} + +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} + + +/***/ }), + +/***/ 530: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var modeModules = { + ECB: __webpack_require__(52632), + CBC: __webpack_require__(92884), + CFB: __webpack_require__(46383), + CFB8: __webpack_require__(86975), + CFB1: __webpack_require__(55264), + OFB: __webpack_require__(46843), + CTR: __webpack_require__(63053), + GCM: __webpack_require__(63053) +} + +var modes = __webpack_require__(3219) + +for (var key in modes) { + modes[key].module = modeModules[modes[key].mode] +} + +module.exports = modes + + +/***/ }), + +/***/ 46843: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var xor = __webpack_require__(30295) + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + + +/***/ }), + +/***/ 50650: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var aes = __webpack_require__(50462) +var Buffer = (__webpack_require__(92861).Buffer) +var Transform = __webpack_require__(56168) +var inherits = __webpack_require__(56698) + +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._mode = mode +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} + +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} + +module.exports = StreamCipher + + +/***/ }), + +/***/ 30125: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var DES = __webpack_require__(84050) +var aes = __webpack_require__(1241) +var aesModes = __webpack_require__(530) +var desModes = __webpack_require__(32438) +var ebtk = __webpack_require__(68078) + +function createCipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) +} + +function createDecipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createDecipheriv(suite, keys.key, keys.iv) +} + +function createCipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createCipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }) + + throw new TypeError('invalid suite type') +} + +function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) + + throw new TypeError('invalid suite type') +} + +function getCiphers () { + return Object.keys(desModes).concat(aes.getCiphers()) +} + +exports.createCipher = exports.Cipher = createCipher +exports.createCipheriv = exports.Cipheriv = createCipheriv +exports.createDecipher = exports.Decipher = createDecipher +exports.createDecipheriv = exports.Decipheriv = createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + + +/***/ }), + +/***/ 84050: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var CipherBase = __webpack_require__(56168) +var des = __webpack_require__(29560) +var inherits = __webpack_require__(56698) +var Buffer = (__webpack_require__(92861).Buffer) + +var modes = { + 'des-ede3-cbc': des.CBC.instantiate(des.EDE), + 'des-ede3': des.EDE, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES +} +modes.des = modes['des-cbc'] +modes.des3 = modes['des-ede3-cbc'] +module.exports = DES +inherits(DES, CipherBase) +function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (!Buffer.isBuffer(key)) { + key = Buffer.from(key) + } + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + if (!Buffer.isBuffer(iv)) { + iv = Buffer.from(iv) + } + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) +} +DES.prototype._update = function (data) { + return Buffer.from(this._des.update(data)) +} +DES.prototype._final = function () { + return Buffer.from(this._des.final()) +} + + +/***/ }), + +/***/ 32438: +/***/ ((__unused_webpack_module, exports) => { + +exports["des-ecb"] = { + key: 8, + iv: 0 +} +exports["des-cbc"] = exports.des = { + key: 8, + iv: 8 +} +exports["des-ede3-cbc"] = exports.des3 = { + key: 24, + iv: 8 +} +exports["des-ede3"] = { + key: 24, + iv: 0 +} +exports["des-ede-cbc"] = { + key: 16, + iv: 8 +} +exports["des-ede"] = { + key: 16, + iv: 0 +} + + +/***/ }), + +/***/ 67332: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var BN = __webpack_require__(39404) +var randomBytes = __webpack_require__(53209) + +function blind (priv) { + var r = getr(priv) + var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed() + return { blinder: blinder, unblinder: r.invm(priv.modulus) } +} + +function getr (priv) { + var len = priv.modulus.byteLength() + var r + do { + r = new BN(randomBytes(len)) + } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) + return r +} + +function crt (msg, priv) { + var blinds = blind(priv) + var len = priv.modulus.byteLength() + var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus) + var c1 = blinded.toRed(BN.mont(priv.prime1)) + var c2 = blinded.toRed(BN.mont(priv.prime2)) + var qinv = priv.coefficient + var p = priv.prime1 + var q = priv.prime2 + var m1 = c1.redPow(priv.exponent1).fromRed() + var m2 = c2.redPow(priv.exponent2).fromRed() + var h = m1.isub(m2).imul(qinv).umod(p).imul(q) + return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len) +} +crt.getr = getr + +module.exports = crt + + +/***/ }), + +/***/ 55715: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = __webpack_require__(62951); + + +/***/ }), + +/***/ 20: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Buffer = (__webpack_require__(92861).Buffer); +var createHash = __webpack_require__(47108); +var stream = __webpack_require__(46737); +var inherits = __webpack_require__(56698); +var sign = __webpack_require__(35359); +var verify = __webpack_require__(74847); + +var algorithms = __webpack_require__(62951); +Object.keys(algorithms).forEach(function (key) { + algorithms[key].id = Buffer.from(algorithms[key].id, 'hex'); + algorithms[key.toLowerCase()] = algorithms[key]; +}); + +function Sign(algorithm) { + stream.Writable.call(this); + + var data = algorithms[algorithm]; + if (!data) { throw new Error('Unknown message digest'); } + + this._hashType = data.hash; + this._hash = createHash(data.hash); + this._tag = data.id; + this._signType = data.sign; +} +inherits(Sign, stream.Writable); + +Sign.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; + +Sign.prototype.update = function update(data, enc) { + this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data); + + return this; +}; + +Sign.prototype.sign = function signMethod(key, enc) { + this.end(); + var hash = this._hash.digest(); + var sig = sign(hash, key, this._hashType, this._signType, this._tag); + + return enc ? sig.toString(enc) : sig; +}; + +function Verify(algorithm) { + stream.Writable.call(this); + + var data = algorithms[algorithm]; + if (!data) { throw new Error('Unknown message digest'); } + + this._hash = createHash(data.hash); + this._tag = data.id; + this._signType = data.sign; +} +inherits(Verify, stream.Writable); + +Verify.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; + +Verify.prototype.update = function update(data, enc) { + this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data); + + return this; +}; + +Verify.prototype.verify = function verifyMethod(key, sig, enc) { + var sigBuffer = typeof sig === 'string' ? Buffer.from(sig, enc) : sig; + + this.end(); + var hash = this._hash.digest(); + return verify(sigBuffer, hash, key, this._signType, this._tag); +}; + +function createSign(algorithm) { + return new Sign(algorithm); +} + +function createVerify(algorithm) { + return new Verify(algorithm); +} + +module.exports = { + Sign: createSign, + Verify: createVerify, + createSign: createSign, + createVerify: createVerify +}; + + +/***/ }), + +/***/ 35359: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var Buffer = (__webpack_require__(92861).Buffer); +var createHmac = __webpack_require__(83507); +var crt = __webpack_require__(67332); +var EC = (__webpack_require__(86729).ec); +var BN = __webpack_require__(39404); +var parseKeys = __webpack_require__(78170); +var curves = __webpack_require__(64589); + +var RSA_PKCS1_PADDING = 1; + +function sign(hash, key, hashType, signType, tag) { + var priv = parseKeys(key); + if (priv.curve) { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); } + return ecSign(hash, priv); + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') { throw new Error('wrong private key type'); } + return dsaSign(hash, priv, hashType); + } + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); } + if (key.padding !== undefined && key.padding !== RSA_PKCS1_PADDING) { throw new Error('illegal or unsupported padding mode'); } + + hash = Buffer.concat([tag, hash]); + var len = priv.modulus.byteLength(); + var pad = [0, 1]; + while (hash.length + pad.length + 1 < len) { pad.push(0xff); } + pad.push(0x00); + var i = -1; + while (++i < hash.length) { pad.push(hash[i]); } + + var out = crt(pad, priv); + return out; +} + +function ecSign(hash, priv) { + var curveId = curves[priv.curve.join('.')]; + if (!curveId) { throw new Error('unknown curve ' + priv.curve.join('.')); } + + var curve = new EC(curveId); + var key = curve.keyFromPrivate(priv.privateKey); + var out = key.sign(hash); + + return Buffer.from(out.toDER()); +} + +function dsaSign(hash, priv, algo) { + var x = priv.params.priv_key; + var p = priv.params.p; + var q = priv.params.q; + var g = priv.params.g; + var r = new BN(0); + var k; + var H = bits2int(hash, q).mod(q); + var s = false; + var kv = getKey(x, q, hash, algo); + while (s === false) { + k = makeKey(q, kv, algo); + r = makeR(g, k, p, q); + s = k.invm(q).imul(H.add(x.mul(r))).mod(q); + if (s.cmpn(0) === 0) { + s = false; + r = new BN(0); + } + } + return toDER(r, s); +} + +function toDER(r, s) { + r = r.toArray(); + s = s.toArray(); + + // Pad values + if (r[0] & 0x80) { r = [0].concat(r); } + if (s[0] & 0x80) { s = [0].concat(s); } + + var total = r.length + s.length + 4; + var res = [ + 0x30, total, 0x02, r.length + ]; + res = res.concat(r, [0x02, s.length], s); + return Buffer.from(res); +} + +function getKey(x, q, hash, algo) { + x = Buffer.from(x.toArray()); + if (x.length < q.byteLength()) { + var zeros = Buffer.alloc(q.byteLength() - x.length); + x = Buffer.concat([zeros, x]); + } + var hlen = hash.length; + var hbits = bits2octets(hash, q); + var v = Buffer.alloc(hlen); + v.fill(1); + var k = Buffer.alloc(hlen); + k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + return { k: k, v: v }; +} + +function bits2int(obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { bits.ishrn(shift); } + return bits; +} + +function bits2octets(bits, q) { + bits = bits2int(bits, q); + bits = bits.mod(q); + var out = Buffer.from(bits.toArray()); + if (out.length < q.byteLength()) { + var zeros = Buffer.alloc(q.byteLength() - out.length); + out = Buffer.concat([zeros, out]); + } + return out; +} + +function makeKey(q, kv, algo) { + var t; + var k; + + do { + t = Buffer.alloc(0); + + while (t.length * 8 < q.bitLength()) { + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + t = Buffer.concat([t, kv.v]); + } + + k = bits2int(t, q); + kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest(); + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + } while (k.cmp(q) !== -1); + + return k; +} + +function makeR(g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); +} + +module.exports = sign; +module.exports.getKey = getKey; +module.exports.makeKey = makeKey; + + +/***/ }), + +/***/ 74847: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var Buffer = (__webpack_require__(92861).Buffer); +var BN = __webpack_require__(39404); +var EC = (__webpack_require__(86729).ec); +var parseKeys = __webpack_require__(78170); +var curves = __webpack_require__(64589); + +function verify(sig, hash, key, signType, tag) { + var pub = parseKeys(key); + if (pub.type === 'ec') { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); } + return ecVerify(sig, hash, pub); + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') { throw new Error('wrong public key type'); } + return dsaVerify(sig, hash, pub); + } + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); } + + hash = Buffer.concat([tag, hash]); + var len = pub.modulus.byteLength(); + var pad = [1]; + var padNum = 0; + while (hash.length + pad.length + 2 < len) { + pad.push(0xff); + padNum += 1; + } + pad.push(0x00); + var i = -1; + while (++i < hash.length) { + pad.push(hash[i]); + } + pad = Buffer.from(pad); + var red = BN.mont(pub.modulus); + sig = new BN(sig).toRed(red); + + sig = sig.redPow(new BN(pub.publicExponent)); + sig = Buffer.from(sig.fromRed().toArray()); + var out = padNum < 8 ? 1 : 0; + len = Math.min(sig.length, pad.length); + if (sig.length !== pad.length) { out = 1; } + + i = -1; + while (++i < len) { out |= sig[i] ^ pad[i]; } + return out === 0; +} + +function ecVerify(sig, hash, pub) { + var curveId = curves[pub.data.algorithm.curve.join('.')]; + if (!curveId) { throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')); } + + var curve = new EC(curveId); + var pubkey = pub.data.subjectPrivateKey.data; + + return curve.verify(hash, sig, pubkey); +} + +function dsaVerify(sig, hash, pub) { + var p = pub.data.p; + var q = pub.data.q; + var g = pub.data.g; + var y = pub.data.pub_key; + var unpacked = parseKeys.signature.decode(sig, 'der'); + var s = unpacked.s; + var r = unpacked.r; + checkValue(s, q); + checkValue(r, q); + var montp = BN.mont(p); + var w = s.invm(q); + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .mod(q); + return v.cmp(r) === 0; +} + +function checkValue(b, q) { + if (b.cmpn(0) <= 0) { throw new Error('invalid sig'); } + if (b.cmp(q) >= 0) { throw new Error('invalid sig'); } +} + +module.exports = verify; + + +/***/ }), + +/***/ 32240: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 26248: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(33225); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(15622)); +util.inherits = __webpack_require__(56698); +/**/ + +var Readable = __webpack_require__(30206); +var Writable = __webpack_require__(7314); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 75242: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(81816); + +/**/ +var util = Object.create(__webpack_require__(15622)); +util.inherits = __webpack_require__(56698); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 30206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(33225); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(32240); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(37007).EventEmitter); + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(5567); +/**/ + +/**/ + +var Buffer = (__webpack_require__(24116).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(15622)); +util.inherits = __webpack_require__(56698); +/**/ + +/**/ +var debugUtil = __webpack_require__(92668); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(20672); +var destroyImpl = __webpack_require__(36278); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(26248); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__webpack_require__(6427)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(26248); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__webpack_require__(6427)/* .StringDecoder */ .I); + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 81816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(26248); + +/**/ +var util = Object.create(__webpack_require__(15622)); +util.inherits = __webpack_require__(56698); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 7314: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(33225); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(15622)); +util.inherits = __webpack_require__(56698); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(94643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(5567); +/**/ + +/**/ + +var Buffer = (__webpack_require__(24116).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(36278); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(26248); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(26248); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 20672: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = (__webpack_require__(24116).Buffer); +var util = __webpack_require__(21638); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 36278: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(33225); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } + + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 5567: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(37007).EventEmitter; + + +/***/ }), + +/***/ 24116: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(48287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 46737: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(30206); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(7314); +exports.Duplex = __webpack_require__(26248); +exports.Transform = __webpack_require__(81816); +exports.PassThrough = __webpack_require__(75242); + + +/***/ }), + +/***/ 6427: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = (__webpack_require__(88393).Buffer); +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.I = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 88393: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(48287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 5974: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +/* provided dependency */ var process = __webpack_require__(65606); + +/* eslint camelcase: "off" */ + +var assert = __webpack_require__(94148); + +var Zstream = __webpack_require__(44442); +var zlib_deflate = __webpack_require__(58411); +var zlib_inflate = __webpack_require__(71447); +var constants = __webpack_require__(19681); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +var GZIP_HEADER_ID1 = 0x1f; +var GZIP_HEADER_ID2 = 0x8b; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError('Bad argument'); + } + + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; +} + +Zlib.prototype.close = function () { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + assert(this.init_done, 'close before init'); + assert(this.mode <= exports.UNZIP); + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; + + this.dictionary = null; +}; + +Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { + assert.equal(arguments.length, 8); + + assert(this.init_done, 'write before init'); + assert(this.mode !== exports.NONE, 'already finalized'); + assert.equal(false, this.write_in_progress, 'write already in progress'); + assert.equal(false, this.pending_close, 'close is pending'); + + this.write_in_progress = true; + + assert.equal(false, flush === undefined, 'must provide flush value'); + + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + + if (!async) { + // sync version + this._process(); + + if (this._checkError()) { + return this._afterSync(); + } + return; + } + + // async version + var self = this; + process.nextTick(function () { + self._process(); + self._after(); + }); + + return this; +}; + +Zlib.prototype._afterSync = function () { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + return [avail_in, avail_out]; +}; + +Zlib.prototype._process = function () { + var next_expected_header_byte = null; + + // If the avail_out is left at 0, then it means that it ran out + // of room. If there was avail_out left over, then it means + // that all of the input was consumed. + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + + if (this.strm.avail_in === 1) { + // The only available byte was already read. + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + // There is no actual difference between INFLATE and INFLATERAW + // (after initialization). + this.mode = exports.INFLATE; + } + + break; + default: + throw new Error('invalid number of gzip magic number bytes read'); + } + + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate(this.strm, this.flush + + // If data was encoded with dictionary + );if (this.err === exports.Z_NEED_DICT && this.dictionary) { + // Load it + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + // And try to decode again + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. + // Make it possible for After() to tell a bad dictionary from bad + // input. + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { + // Bytes remain in input buffer. Perhaps this is another compressed + // member in the same archive, or just trailing garbage. + // Trailing zero bytes are okay, though, since they are frequently + // used for padding. + + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error('Unknown mode ' + this.mode); + } +}; + +Zlib.prototype._checkError = function () { + // Acceptable error states depend on the type of zlib stream. + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error('unexpected end of file'); + return false; + } + break; + case exports.Z_STREAM_END: + // normal statuses, not fatal + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error('Missing dictionary'); + } else { + this._error('Bad dictionary'); + } + return false; + default: + // something else. + this._error('Zlib error'); + return false; + } + + return true; +}; + +Zlib.prototype._after = function () { + if (!this._checkError()) { + return; + } + + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + // call the write() cb + this.callback(avail_in, avail_out); + + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype._error = function (message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror(message, this.err + + // no hope of rescue. + );this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { + assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); + + assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); + assert(level >= -1 && level <= 9, 'invalid compression level'); + + assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); + + assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); + + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); +}; + +Zlib.prototype.params = function () { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype.reset = function () { + this._reset(); + this._setDictionary(); +}; + +Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + + this.flush = exports.Z_NO_FLUSH; + + this.err = exports.Z_OK; + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + + this.strm = new Zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (this.err !== exports.Z_OK) { + this._error('Init error'); + } + + this.dictionary = dictionary; + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype._setDictionary = function () { + if (this.dictionary == null) { + return; + } + + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to set dictionary'); + } +}; + +Zlib.prototype._reset = function () { + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to reset stream'); + } +}; + +exports.Zlib = Zlib; + +/***/ }), + +/***/ 78559: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +var Buffer = (__webpack_require__(48287).Buffer); +var Transform = (__webpack_require__(88310).Transform); +var binding = __webpack_require__(5974); +var util = __webpack_require__(40537); +var assert = (__webpack_require__(94148).ok); +var kMaxLength = (__webpack_require__(48287).kMaxLength); +var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = 16 * 1024; + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +var bkeys = Object.keys(binding); +for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, value: binding[bkey], writable: false + }); + } +} + +// translation table for return codes. +var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +var ckeys = Object.keys(codes); +for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; +} + +Object.defineProperty(exports, "codes", ({ + enumerable: true, value: Object.freeze(codes), writable: false +})); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function (o) { + return new Deflate(o); +}; + +exports.createInflate = function (o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function (o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function (o) { + return new InflateRaw(o); +}; + +exports.createGzip = function (o) { + return new Gzip(o); +}; + +exports.createGunzip = function (o) { + return new Gunzip(o); +}; + +exports.createUnzip = function (o) { + return new Unzip(o); +}; + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function (buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function (buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function (buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function (buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function (buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function (buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function (buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf; + var err = null; + + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer.concat(buffers, nread); + } + + buffers = []; + engine.close(); + callback(err, buf); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') buffer = Buffer.from(buffer); + + if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); + + var flushFlag = engine._finishFlushFlag; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + +function isValidFlushFlag(flag) { + return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + var _this = this; + + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error('Invalid flush flag: ' + opts.finishFlush); + } + + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._handle = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._handle.onerror = function (message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + _close(self); + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + + this._buffer = Buffer.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + + Object.defineProperty(this, '_closed', { + get: function () { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function (level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function () { + assert(self._handle, 'zlib binding closed'); + self._handle.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function () { + assert(this._handle, 'zlib binding closed'); + return this._handle.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function (callback) { + this._transform(Buffer.alloc(0), '', callback); +}; + +Zlib.prototype.flush = function (kind, callback) { + var _this2 = this; + + var ws = this._writableState; + + if (typeof kind === 'function' || kind === undefined && !callback) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) process.nextTick(callback); + } else if (ws.ending) { + if (callback) this.once('end', callback); + } else if (ws.needDrain) { + if (callback) { + this.once('drain', function () { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer.alloc(0), '', callback); + } +}; + +Zlib.prototype.close = function (callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); +}; + +function _close(engine, callback) { + if (callback) process.nextTick(callback); + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) return; + + engine._handle.close(); + engine._handle = null; +} + +function emitCloseNT(self) { + self.emit('close'); +} + +Zlib.prototype._transform = function (chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); + + if (!this._handle) return cb(new Error('zlib binding closed')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag + // (or whatever flag was provided using opts.finishFlush). + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) flushFlag = this._finishFlushFlag;else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function (er) { + error = er; + }); + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; + } + + assert(this._handle, 'zlib binding closed'); + var req = this._handle.write(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + // When the callback is used in an async write, the callback's + // context is the `req` object that was created. The req object + // is === this._handle, and that's why it's important to null + // out the values after they are done being used. `this._handle` + // can stay in memory longer than the callback and buffer are needed. + if (this) { + this.buffer = null; + this.callback = null; + } + + if (self._hadError) return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + if (!async) return true; + + var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); + +/***/ }), + +/***/ 30295: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} + + +/***/ }), + +/***/ 48287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(96763); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(67526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 86866: +/***/ ((module) => { + +module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} + + +/***/ }), + +/***/ 38075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(70453); + +var callBind = __webpack_require__(10487); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 10487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(66743); +var GetIntrinsic = __webpack_require__(70453); +var setFunctionLength = __webpack_require__(96897); + +var $TypeError = __webpack_require__(69675); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = __webpack_require__(30655); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ 56168: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) +var Transform = (__webpack_require__(88310).Transform) +var StringDecoder = (__webpack_require__(83141)/* .StringDecoder */ .I) +var inherits = __webpack_require__(56698) + +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null +} +inherits(CipherBase, Transform) + +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out +} + +module.exports = CipherBase + + +/***/ }), + +/***/ 96763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global window, global*/ +var util = __webpack_require__(40537) +var assert = __webpack_require__(94148) +function now() { return new Date().getTime() } + +var slice = Array.prototype.slice +var console +var times = {} + +if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) { + console = __webpack_require__.g.console +} else if (typeof window !== "undefined" && window.console) { + console = window.console +} else { + console = {} +} + +var functions = [ + [log, "log"], + [info, "info"], + [warn, "warn"], + [error, "error"], + [time, "time"], + [timeEnd, "timeEnd"], + [trace, "trace"], + [dir, "dir"], + [consoleAssert, "assert"] +] + +for (var i = 0; i < functions.length; i++) { + var tuple = functions[i] + var f = tuple[0] + var name = tuple[1] + + if (!console[name]) { + console[name] = f + } +} + +module.exports = console + +function log() {} + +function info() { + console.log.apply(console, arguments) +} + +function warn() { + console.log.apply(console, arguments) +} + +function error() { + console.warn.apply(console, arguments) +} + +function time(label) { + times[label] = now() +} + +function timeEnd(label) { + var time = times[label] + if (!time) { + throw new Error("No such label: " + label) + } + + delete times[label] + var duration = now() - time + console.log(label + ": " + duration + "ms") +} + +function trace() { + var err = new Error() + err.name = "Trace" + err.message = util.format.apply(null, arguments) + console.error(err.stack) +} + +function dir(object) { + console.log(util.inspect(object) + "\n") +} + +function consoleAssert(expression) { + if (!expression) { + var arr = slice.call(arguments, 1) + assert.ok(false, util.format.apply(null, arr)) + } +} + + +/***/ }), + +/***/ 15622: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(48287).Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 61324: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var elliptic = __webpack_require__(86729) +var BN = __webpack_require__(92801) + +module.exports = function createECDH (curve) { + return new ECDH(curve) +} + +var aliases = { + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +} + +aliases.p224 = aliases.secp224r1 +aliases.p256 = aliases.secp256r1 = aliases.prime256v1 +aliases.p192 = aliases.secp192r1 = aliases.prime192v1 +aliases.p384 = aliases.secp384r1 +aliases.p521 = aliases.secp521r1 + +function ECDH (curve) { + this.curveType = aliases[curve] + if (!this.curveType) { + this.curveType = { + name: curve + } + } + this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap + this.keys = void 0 +} + +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair() + return this.getPublicKey(enc, format) +} + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8' + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc) + } + var otherPub = this.curve.keyFromPublic(other).getPublic() + var out = otherPub.mul(this.keys.getPrivate()).getX() + return formatReturnValue(out, enc, this.curveType.byteLength) +} + +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true) + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7 + } else { + key[0] = 6 + } + } + return formatReturnValue(key, enc) +} + +ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc) +} + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc) + } + this.keys._importPublic(pub) + return this +} + +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc) + } + + var _priv = new BN(priv) + _priv = _priv.toString(16) + this.keys = this.curve.genKeyPair() + this.keys._importPrivate(_priv) + return this +} + +function formatReturnValue (bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray() + } + var buf = new Buffer(bn) + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length) + zeros.fill(0) + buf = Buffer.concat([zeros, buf]) + } + if (!enc) { + return buf + } else { + return buf.toString(enc) + } +} + + +/***/ }), + +/***/ 92801: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(77965).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 47108: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(56698) +var MD5 = __webpack_require__(88276) +var RIPEMD160 = __webpack_require__(66011) +var sha = __webpack_require__(62802) +var Base = __webpack_require__(56168) + +function Hash (hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) +} + + +/***/ }), + +/***/ 20320: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var MD5 = __webpack_require__(88276) + +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} + + +/***/ }), + +/***/ 83507: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(56698) +var Legacy = __webpack_require__(41800) +var Base = __webpack_require__(56168) +var Buffer = (__webpack_require__(92861).Buffer) +var md5 = __webpack_require__(20320) +var RIPEMD160 = __webpack_require__(66011) + +var sha = __webpack_require__(62802) + +var ZEROS = Buffer.alloc(128) + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.update(data) +} + +Hmac.prototype._final = function () { + var h = this._hash.digest() + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() +} + +module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) +} + + +/***/ }), + +/***/ 41800: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(56698) +var Buffer = (__webpack_require__(92861).Buffer) + +var Base = __webpack_require__(56168) + +var ZEROS = Buffer.alloc(128) +var blocksize = 64 + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = alg(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = [ipad] +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.push(data) +} + +Hmac.prototype._final = function () { + var h = this._alg(Buffer.concat(this._hash)) + return this._alg(Buffer.concat([this._opad, h])) +} +module.exports = Hmac + + +/***/ }), + +/***/ 74945: +/***/ ((module, exports, __webpack_require__) => { + +// Save global object in a variable +var __global__ = +(typeof globalThis !== 'undefined' && globalThis) || +(typeof self !== 'undefined' && self) || +(typeof __webpack_require__.g !== 'undefined' && __webpack_require__.g); +// Create an object that extends from __global__ without the fetch function +var __globalThis__ = (function () { +function F() { +this.fetch = false; +this.DOMException = __global__.DOMException +} +F.prototype = __global__; // Needed for feature detection on whatwg-fetch's code +return new F(); +})(); +// Wraps whatwg-fetch with a function scope to hijack the global object +// "globalThis" that's going to be patched +(function(globalThis) { + +var irrelevant = (function (exports) { + + var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof self !== 'undefined' && self) || + (typeof global !== 'undefined' && global); + + var support = { + searchParams: 'URLSearchParams' in global, + iterable: 'Symbol' in global && 'iterator' in Symbol, + blob: + 'FileReader' in global && + 'Blob' in global && + (function() { + try { + new Blob(); + return true + } catch (e) { + return false + } + })(), + formData: 'FormData' in global, + arrayBuffer: 'ArrayBuffer' in global + }; + + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; + + var isArrayBufferView = + ArrayBuffer.isView || + function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + }; + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') { + throw new TypeError('Invalid character in header field name: "' + name + '"') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return {done: value === undefined, value: value} + } + }; + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + }; + } + + return iterator + } + + function Headers(headers) { + this.map = {}; + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ', ' + value : value; + }; + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)]; + }; + + Headers.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null + }; + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + }; + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + Headers.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items) + }; + + Headers.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items) + }; + + Headers.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items) + }; + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true; + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + /* + fetch-mock wraps the Response object in an ES6 Proxy to + provide useful test harness features such as flush. However, on + ES5 browsers without fetch or Proxy support pollyfills must be used; + the proxy-pollyfill is unable to proxy an attribute unless it exists + on the object before the Proxy is created. This change ensures + Response.bodyUsed exists on the instance, while maintaining the + semantic of setting Request.bodyUsed in the constructor before + _initBody is called. + */ + this.bodyUsed = this.bodyUsed; + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + var isConsumed = consumed(this); + if (isConsumed) { + return isConsumed + } + if (ArrayBuffer.isView(this._bodyArrayBuffer)) { + return Promise.resolve( + this._bodyArrayBuffer.buffer.slice( + this._bodyArrayBuffer.byteOffset, + this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength + ) + ) + } else { + return Promise.resolve(this._bodyArrayBuffer) + } + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + }; + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + }; + } + + this.json = function() { + return this.text().then(JSON.parse) + }; + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method + } + + function Request(input, options) { + if (!(this instanceof Request)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } + + options = options || {}; + var body = options.body; + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'same-origin'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal; + this.referrer = null; + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body); + + if (this.method === 'GET' || this.method === 'HEAD') { + if (options.cache === 'no-store' || options.cache === 'no-cache') { + // Search for a '_' parameter in the query string + var reParamSearch = /([?&])_=[^&]*/; + if (reParamSearch.test(this.url)) { + // If it already exists then set the value with the current time + this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime()); + } else { + // Otherwise add a new '_' parameter to the end with the current time + var reQueryString = /\?/; + this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime(); + } + } + } + } + + Request.prototype.clone = function() { + return new Request(this, {body: this._bodyInit}) + }; + + function decode(body) { + var form = new FormData(); + body + .trim() + .split('&') + .forEach(function(bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill + // https://github.com/github/fetch/issues/748 + // https://github.com/zloirock/core-js/issues/751 + preProcessedHeaders + .split('\r') + .map(function(header) { + return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header + }) + .forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers + } + + Body.call(Request.prototype); + + function Response(bodyInit, options) { + if (!(this instanceof Response)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } + if (!options) { + options = {}; + } + + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = options.statusText === undefined ? '' : '' + options.statusText; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + }; + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}); + response.type = 'error'; + return response + }; + + var redirectStatuses = [301, 302, 303, 307, 308]; + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + }; + + exports.DOMException = global.DOMException; + try { + new exports.DOMException(); + } catch (err) { + exports.DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + exports.DOMException.prototype = Object.create(Error.prototype); + exports.DOMException.prototype.constructor = exports.DOMException; + } + + function fetch(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); + + if (request.signal && request.signal.aborted) { + return reject(new exports.DOMException('Aborted', 'AbortError')) + } + + var xhr = new XMLHttpRequest(); + + function abortXhr() { + xhr.abort(); + } + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + setTimeout(function() { + resolve(new Response(body, options)); + }, 0); + }; + + xhr.onerror = function() { + setTimeout(function() { + reject(new TypeError('Network request failed')); + }, 0); + }; + + xhr.ontimeout = function() { + setTimeout(function() { + reject(new TypeError('Network request failed')); + }, 0); + }; + + xhr.onabort = function() { + setTimeout(function() { + reject(new exports.DOMException('Aborted', 'AbortError')); + }, 0); + }; + + function fixUrl(url) { + try { + return url === '' && global.location.href ? global.location.href : url + } catch (e) { + return url + } + } + + xhr.open(request.method, fixUrl(request.url), true); + + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } + + if ('responseType' in xhr) { + if (support.blob) { + xhr.responseType = 'blob'; + } else if ( + support.arrayBuffer && + request.headers.get('Content-Type') && + request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1 + ) { + xhr.responseType = 'arraybuffer'; + } + } + + if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) { + Object.getOwnPropertyNames(init.headers).forEach(function(name) { + xhr.setRequestHeader(name, normalizeValue(init.headers[name])); + }); + } else { + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + } + + if (request.signal) { + request.signal.addEventListener('abort', abortXhr); + + xhr.onreadystatechange = function() { + // DONE (success or failure) + if (xhr.readyState === 4) { + request.signal.removeEventListener('abort', abortXhr); + } + }; + } + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }) + } + + fetch.polyfill = true; + + if (!global.fetch) { + global.fetch = fetch; + global.Headers = Headers; + global.Request = Request; + global.Response = Response; + } + + exports.Headers = Headers; + exports.Request = Request; + exports.Response = Response; + exports.fetch = fetch; + + return exports; + +})({}); +})(__globalThis__); +// This is a ponyfill, so... +__globalThis__.fetch.ponyfill = true; +delete __globalThis__.fetch.polyfill; +// Choose between native implementation (__global__) or custom implementation (__globalThis__) +var ctx = __global__.fetch ? __global__ : __globalThis__; +exports = ctx.fetch // To enable: import fetch from 'cross-fetch' +exports["default"] = ctx.fetch // For TypeScript consumers without esModuleInterop. +exports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch' +exports.Headers = ctx.Headers +exports.Request = ctx.Request +exports.Response = ctx.Response +module.exports = exports + + +/***/ }), + +/***/ 91565: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(53209) +exports.createHash = exports.Hash = __webpack_require__(47108) +exports.createHmac = exports.Hmac = __webpack_require__(83507) + +var algos = __webpack_require__(55715) +var algoKeys = Object.keys(algos) +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) +exports.getHashes = function () { + return hashes +} + +var p = __webpack_require__(78396) +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync + +var aes = __webpack_require__(30125) + +exports.Cipher = aes.Cipher +exports.createCipher = aes.createCipher +exports.Cipheriv = aes.Cipheriv +exports.createCipheriv = aes.createCipheriv +exports.Decipher = aes.Decipher +exports.createDecipher = aes.createDecipher +exports.Decipheriv = aes.Decipheriv +exports.createDecipheriv = aes.createDecipheriv +exports.getCiphers = aes.getCiphers +exports.listCiphers = aes.listCiphers + +var dh = __webpack_require__(15380) + +exports.DiffieHellmanGroup = dh.DiffieHellmanGroup +exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup +exports.getDiffieHellman = dh.getDiffieHellman +exports.createDiffieHellman = dh.createDiffieHellman +exports.DiffieHellman = dh.DiffieHellman + +var sign = __webpack_require__(20) + +exports.createSign = sign.createSign +exports.Sign = sign.Sign +exports.createVerify = sign.createVerify +exports.Verify = sign.Verify + +exports.createECDH = __webpack_require__(61324) + +var publicEncrypt = __webpack_require__(97168) + +exports.publicEncrypt = publicEncrypt.publicEncrypt +exports.privateEncrypt = publicEncrypt.privateEncrypt +exports.publicDecrypt = publicEncrypt.publicDecrypt +exports.privateDecrypt = publicEncrypt.privateDecrypt + +// the least I can do is make error messages for the rest of the node.js/crypto api. +// ;[ +// 'createCredentials' +// ].forEach(function (name) { +// exports[name] = function () { +// throw new Error([ +// 'sorry, ' + name + ' is not implemented yet', +// 'we accept pull requests', +// 'https://github.com/crypto-browserify/crypto-browserify' +// ].join('\n')) +// } +// }) + +var rf = __webpack_require__(76983) + +exports.randomFill = rf.randomFill +exports.randomFillSync = rf.randomFillSync + +exports.createCredentials = function () { + throw new Error([ + 'sorry, createCredentials is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) +} + +exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + 'POINT_CONVERSION_UNCOMPRESSED': 4, + 'POINT_CONVERSION_HYBRID': 6 +} + + +/***/ }), + +/***/ 17833: +/***/ ((module, exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); +/* provided dependency */ var process = __webpack_require__(65606); +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = __webpack_require__(40736)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + + +/***/ }), + +/***/ 40736: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(6585); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 30041: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(30655); + +var $SyntaxError = __webpack_require__(58068); +var $TypeError = __webpack_require__(69675); + +var gopd = __webpack_require__(75795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ 38452: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keys = __webpack_require__(1189); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var defineDataProperty = __webpack_require__(30041); + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var supportsDescriptors = __webpack_require__(30592)(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; + + +/***/ }), + +/***/ 29560: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.utils = __webpack_require__(87626); +exports.Cipher = __webpack_require__(82808); +exports.DES = __webpack_require__(82211); +exports.CBC = __webpack_require__(3389); +exports.EDE = __webpack_require__(65279); + + +/***/ }), + +/***/ 3389: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(43349); +var inherits = __webpack_require__(56698); + +var proto = {}; + +function CBCState(iv) { + assert.equal(iv.length, 8, 'Invalid IV length'); + + this.iv = new Array(8); + for (var i = 0; i < this.iv.length; i++) + this.iv[i] = iv[i]; +} + +function instantiate(Base) { + function CBC(options) { + Base.call(this, options); + this._cbcInit(); + } + inherits(CBC, Base); + + var keys = Object.keys(proto); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + CBC.prototype[key] = proto[key]; + } + + CBC.create = function create(options) { + return new CBC(options); + }; + + return CBC; +} + +exports.instantiate = instantiate; + +proto._cbcInit = function _cbcInit() { + var state = new CBCState(this.options.iv); + this._cbcState = state; +}; + +proto._update = function _update(inp, inOff, out, outOff) { + var state = this._cbcState; + var superProto = this.constructor.super_.prototype; + + var iv = state.iv; + if (this.type === 'encrypt') { + for (var i = 0; i < this.blockSize; i++) + iv[i] ^= inp[inOff + i]; + + superProto._update.call(this, iv, 0, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + iv[i] = out[outOff + i]; + } else { + superProto._update.call(this, inp, inOff, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + out[outOff + i] ^= iv[i]; + + for (var i = 0; i < this.blockSize; i++) + iv[i] = inp[inOff + i]; + } +}; + + +/***/ }), + +/***/ 82808: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(43349); + +function Cipher(options) { + this.options = options; + + this.type = this.options.type; + this.blockSize = 8; + this._init(); + + this.buffer = new Array(this.blockSize); + this.bufferOff = 0; + this.padding = options.padding !== false +} +module.exports = Cipher; + +Cipher.prototype._init = function _init() { + // Might be overrided +}; + +Cipher.prototype.update = function update(data) { + if (data.length === 0) + return []; + + if (this.type === 'decrypt') + return this._updateDecrypt(data); + else + return this._updateEncrypt(data); +}; + +Cipher.prototype._buffer = function _buffer(data, off) { + // Append data to buffer + var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); + for (var i = 0; i < min; i++) + this.buffer[this.bufferOff + i] = data[off + i]; + this.bufferOff += min; + + // Shift next + return min; +}; + +Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { + this._update(this.buffer, 0, out, off); + this.bufferOff = 0; + return this.blockSize; +}; + +Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = ((this.bufferOff + data.length) / this.blockSize) | 0; + var out = new Array(count * this.blockSize); + + if (this.bufferOff !== 0) { + inputOff += this._buffer(data, inputOff); + + if (this.bufferOff === this.buffer.length) + outputOff += this._flushBuffer(out, outputOff); + } + + // Write blocks + var max = data.length - ((data.length - inputOff) % this.blockSize); + for (; inputOff < max; inputOff += this.blockSize) { + this._update(data, inputOff, out, outputOff); + outputOff += this.blockSize; + } + + // Queue rest + for (; inputOff < data.length; inputOff++, this.bufferOff++) + this.buffer[this.bufferOff] = data[inputOff]; + + return out; +}; + +Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; + var out = new Array(count * this.blockSize); + + // TODO(indutny): optimize it, this is far from optimal + for (; count > 0; count--) { + inputOff += this._buffer(data, inputOff); + outputOff += this._flushBuffer(out, outputOff); + } + + // Buffer rest of the input + inputOff += this._buffer(data, inputOff); + + return out; +}; + +Cipher.prototype.final = function final(buffer) { + var first; + if (buffer) + first = this.update(buffer); + + var last; + if (this.type === 'encrypt') + last = this._finalEncrypt(); + else + last = this._finalDecrypt(); + + if (first) + return first.concat(last); + else + return last; +}; + +Cipher.prototype._pad = function _pad(buffer, off) { + if (off === 0) + return false; + + while (off < buffer.length) + buffer[off++] = 0; + + return true; +}; + +Cipher.prototype._finalEncrypt = function _finalEncrypt() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + + var out = new Array(this.blockSize); + this._update(this.buffer, 0, out, 0); + return out; +}; + +Cipher.prototype._unpad = function _unpad(buffer) { + return buffer; +}; + +Cipher.prototype._finalDecrypt = function _finalDecrypt() { + assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); + var out = new Array(this.blockSize); + this._flushBuffer(out, 0); + + return this._unpad(out); +}; + + +/***/ }), + +/***/ 82211: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(43349); +var inherits = __webpack_require__(56698); + +var utils = __webpack_require__(87626); +var Cipher = __webpack_require__(82808); + +function DESState() { + this.tmp = new Array(2); + this.keys = null; +} + +function DES(options) { + Cipher.call(this, options); + + var state = new DESState(); + this._desState = state; + + this.deriveKeys(state, options.key); +} +inherits(DES, Cipher); +module.exports = DES; + +DES.create = function create(options) { + return new DES(options); +}; + +var shiftTable = [ + 1, 1, 2, 2, 2, 2, 2, 2, + 1, 2, 2, 2, 2, 2, 2, 1 +]; + +DES.prototype.deriveKeys = function deriveKeys(state, key) { + state.keys = new Array(16 * 2); + + assert.equal(key.length, this.blockSize, 'Invalid key length'); + + var kL = utils.readUInt32BE(key, 0); + var kR = utils.readUInt32BE(key, 4); + + utils.pc1(kL, kR, state.tmp, 0); + kL = state.tmp[0]; + kR = state.tmp[1]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + utils.pc2(kL, kR, state.keys, i); + } +}; + +DES.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._desState; + + var l = utils.readUInt32BE(inp, inOff); + var r = utils.readUInt32BE(inp, inOff + 4); + + // Initial Permutation + utils.ip(l, r, state.tmp, 0); + l = state.tmp[0]; + r = state.tmp[1]; + + if (this.type === 'encrypt') + this._encrypt(state, l, r, state.tmp, 0); + else + this._decrypt(state, l, r, state.tmp, 0); + + l = state.tmp[0]; + r = state.tmp[1]; + + utils.writeUInt32BE(out, l, outOff); + utils.writeUInt32BE(out, r, outOff + 4); +}; + +DES.prototype._pad = function _pad(buffer, off) { + if (this.padding === false) { + return false; + } + + var value = buffer.length - off; + for (var i = off; i < buffer.length; i++) + buffer[i] = value; + + return true; +}; + +DES.prototype._unpad = function _unpad(buffer) { + if (this.padding === false) { + return buffer; + } + + var pad = buffer[buffer.length - 1]; + for (var i = buffer.length - pad; i < buffer.length; i++) + assert.equal(buffer[i], pad); + + return buffer.slice(0, buffer.length - pad); +}; + +DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { + var l = lStart; + var r = rStart; + + // Apply f() x16 times + for (var i = 0; i < state.keys.length; i += 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(r, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = r; + r = (l ^ f) >>> 0; + l = t; + } + + // Reverse Initial Permutation + utils.rip(r, l, out, off); +}; + +DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { + var l = rStart; + var r = lStart; + + // Apply f() x16 times + for (var i = state.keys.length - 2; i >= 0; i -= 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(l, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = l; + l = (r ^ f) >>> 0; + r = t; + } + + // Reverse Initial Permutation + utils.rip(l, r, out, off); +}; + + +/***/ }), + +/***/ 65279: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(43349); +var inherits = __webpack_require__(56698); + +var Cipher = __webpack_require__(82808); +var DES = __webpack_require__(82211); + +function EDEState(type, key) { + assert.equal(key.length, 24, 'Invalid key length'); + + var k1 = key.slice(0, 8); + var k2 = key.slice(8, 16); + var k3 = key.slice(16, 24); + + if (type === 'encrypt') { + this.ciphers = [ + DES.create({ type: 'encrypt', key: k1 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } +} + +function EDE(options) { + Cipher.call(this, options); + + var state = new EDEState(this.type, this.options.key); + this._edeState = state; +} +inherits(EDE, Cipher); + +module.exports = EDE; + +EDE.create = function create(options) { + return new EDE(options); +}; + +EDE.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._edeState; + + state.ciphers[0]._update(inp, inOff, out, outOff); + state.ciphers[1]._update(out, outOff, out, outOff); + state.ciphers[2]._update(out, outOff, out, outOff); +}; + +EDE.prototype._pad = DES.prototype._pad; +EDE.prototype._unpad = DES.prototype._unpad; + + +/***/ }), + +/***/ 87626: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.readUInt32BE = function readUInt32BE(bytes, off) { + var res = (bytes[0 + off] << 24) | + (bytes[1 + off] << 16) | + (bytes[2 + off] << 8) | + bytes[3 + off]; + return res >>> 0; +}; + +exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { + bytes[0 + off] = value >>> 24; + bytes[1 + off] = (value >>> 16) & 0xff; + bytes[2 + off] = (value >>> 8) & 0xff; + bytes[3 + off] = value & 0xff; +}; + +exports.ip = function ip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.rip = function rip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 0; i < 4; i++) { + for (var j = 24; j >= 0; j -= 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.pc1 = function pc1(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + // 7, 15, 23, 31, 39, 47, 55, 63 + // 6, 14, 22, 30, 39, 47, 55, 63 + // 5, 13, 21, 29, 39, 47, 55, 63 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + + // 1, 9, 17, 25, 33, 41, 49, 57 + // 2, 10, 18, 26, 34, 42, 50, 58 + // 3, 11, 19, 27, 35, 43, 51, 59 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.r28shl = function r28shl(num, shift) { + return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); +}; + +var pc2table = [ + // inL => outL + 14, 11, 17, 4, 27, 23, 25, 0, + 13, 22, 7, 18, 5, 9, 16, 24, + 2, 20, 12, 21, 1, 8, 15, 26, + + // inR => outR + 15, 4, 25, 19, 9, 1, 26, 16, + 5, 11, 23, 8, 12, 7, 17, 0, + 22, 3, 10, 14, 6, 20, 27, 24 +]; + +exports.pc2 = function pc2(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + var len = pc2table.length >>> 1; + for (var i = 0; i < len; i++) { + outL <<= 1; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + outR <<= 1; + outR |= (inR >>> pc2table[i]) & 0x1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.expand = function expand(r, out, off) { + var outL = 0; + var outR = 0; + + outL = ((r & 1) << 5) | (r >>> 27); + for (var i = 23; i >= 15; i -= 4) { + outL <<= 6; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + outR <<= 6; + } + outR |= ((r & 0x1f) << 1) | (r >>> 31); + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +var sTable = [ + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, + + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, + + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, + + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, + + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, + + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, + + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, + + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 +]; + +exports.substitute = function substitute(inL, inR) { + var out = 0; + for (var i = 0; i < 4; i++) { + var b = (inL >>> (18 - i * 6)) & 0x3f; + var sb = sTable[i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + for (var i = 0; i < 4; i++) { + var b = (inR >>> (18 - i * 6)) & 0x3f; + var sb = sTable[4 * 0x40 + i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + return out >>> 0; +}; + +var permuteTable = [ + 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, + 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 +]; + +exports.permute = function permute(num) { + var out = 0; + for (var i = 0; i < permuteTable.length; i++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + return out >>> 0; +}; + +exports.padSplit = function padSplit(num, size, group) { + var str = num.toString(2); + while (str.length < size) + str = '0' + str; + + var out = []; + for (var i = 0; i < size; i += group) + out.push(str.slice(i, i + group)); + return out.join(' '); +}; + + +/***/ }), + +/***/ 15380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var generatePrime = __webpack_require__(4934) +var primes = __webpack_require__(23241) + +var DH = __webpack_require__(14910) + +function getDiffieHellman (mod) { + var prime = new Buffer(primes[mod].prime, 'hex') + var gen = new Buffer(primes[mod].gen, 'hex') + + return new DH(prime, gen) +} + +var ENCODINGS = { + 'binary': true, 'hex': true, 'base64': true +} + +function createDiffieHellman (prime, enc, generator, genc) { + if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { + return createDiffieHellman(prime, 'binary', enc, generator) + } + + enc = enc || 'binary' + genc = genc || 'binary' + generator = generator || new Buffer([2]) + + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc) + } + + if (typeof prime === 'number') { + return new DH(generatePrime(prime, generator), generator, true) + } + + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc) + } + + return new DH(prime, generator, true) +} + +exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman +exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman + + +/***/ }), + +/***/ 14910: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var BN = __webpack_require__(66473); +var MillerRabin = __webpack_require__(52244); +var millerRabin = new MillerRabin(); +var TWENTYFOUR = new BN(24); +var ELEVEN = new BN(11); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var primes = __webpack_require__(4934); +var randomBytes = __webpack_require__(53209); +module.exports = DH; + +function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; +} + +function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; +} + +var primeCache = {}; +function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + return primeCache[hex]; + } + var error = 0; + + if (prime.isEven() || + !primes.simpleSieve || + !primes.fermatTest(prime) || + !millerRabin.test(prime)) { + //not a prime so +1 + error += 1; + + if (gen === '02' || gen === '05') { + // we'd be able to check the generator + // it would fail so +8 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; +} + +function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } +} +Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } +}); +DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); +}; + +DH.prototype.computeSecret = function (other) { + other = new BN(other); + other = other.toRed(this._prime); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; +}; + +DH.prototype.getPublicKey = function getPublicKey(enc) { + return formatReturnValue(this._pub, enc); +}; + +DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return formatReturnValue(this._priv, enc); +}; + +DH.prototype.getPrime = function (enc) { + return formatReturnValue(this.__prime, enc); +}; + +DH.prototype.getGenerator = function (enc) { + return formatReturnValue(this._gen, enc); +}; + +DH.prototype.setGenerator = function (gen, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; +}; + +function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} + + +/***/ }), + +/***/ 4934: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var randomBytes = __webpack_require__(53209); +module.exports = findPrime; +findPrime.simpleSieve = simpleSieve; +findPrime.fermatTest = fermatTest; +var BN = __webpack_require__(66473); +var TWENTYFOUR = new BN(24); +var MillerRabin = __webpack_require__(52244); +var millerRabin = new MillerRabin(); +var ONE = new BN(1); +var TWO = new BN(2); +var FIVE = new BN(5); +var SIXTEEN = new BN(16); +var EIGHT = new BN(8); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var ELEVEN = new BN(11); +var FOUR = new BN(4); +var TWELVE = new BN(12); +var primes = null; + +function _getPrimes() { + if (primes !== null) + return primes; + + var limit = 0x100000; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + + if (i !== j && res[j] <= sqrt) + continue; + + res[i++] = k; + } + primes = res; + return res; +} + +function simpleSieve(p) { + var primes = _getPrimes(); + + for (var i = 0; i < primes.length; i++) + if (p.modn(primes[i]) === 0) { + if (p.cmpn(primes[i]) === 0) { + return true; + } else { + return false; + } + } + + return true; +} + +function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; +} + +function findPrime(bits, gen) { + if (bits < 16) { + // this is what openssl does + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + +} + + +/***/ }), + +/***/ 66473: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(66089).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 86729: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var elliptic = exports; + +elliptic.version = (__webpack_require__(1636)/* .version */ .rE); +elliptic.utils = __webpack_require__(47011); +elliptic.rand = __webpack_require__(15037); +elliptic.curve = __webpack_require__(894); +elliptic.curves = __webpack_require__(60480); + +// Protocols +elliptic.ec = __webpack_require__(57447); +elliptic.eddsa = __webpack_require__(8650); + + +/***/ }), + +/***/ 36677: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); +var utils = __webpack_require__(47011); +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + + this._bitLength = this.n ? this.n.bitLength() : 0; + + // Generalized Greg Maxwell's trick + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + var j; + var nafW; + for (j = 0; j < naf.length; j += doubles.step) { + nafW = 0; + for (var l = j + doubles.step - 1; l >= j; l--) + nafW = (nafW << 1) + naf[l]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (j = 0; j < repr.length; j++) { + nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w, this._bitLength); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var l = 0; i >= 0 && naf[i] === 0; i--) + l++; + if (i >= 0) + l++; + acc = acc.dblp(l); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + var i; + var j; + var p; + for (i = 0; i < len; i++) { + p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); + naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3, /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (j = 0; j < len; j++) { + var z = tmp[j]; + p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null, + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles, + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res, + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + + +/***/ }), + +/***/ 31298: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(47011); +var BN = __webpack_require__(28490); +var inherits = __webpack_require__(56698); +var Base = __webpack_require__(36677); + +var assert = utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + var e; + var h; + var j; + if (this.curve.twisted) { + // E = a * C + e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + h = this.z.redSqr(); + // J = F - 2 * H + j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + e = c.redAdd(d); + // H = (c * Z1)^2 + h = this.curve._mulC(this.z).redSqr(); + // J = E - 2 * H + j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + + +/***/ }), + +/***/ 894: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curve = exports; + +curve.base = __webpack_require__(36677); +curve.short = __webpack_require__(39188); +curve.mont = __webpack_require__(30370); +curve.edwards = __webpack_require__(31298); + + +/***/ }), + +/***/ 30370: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); +var inherits = __webpack_require__(56698); +var Base = __webpack_require__(36677); + +var utils = __webpack_require__(47011); + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + + +/***/ }), + +/***/ 39188: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(47011); +var BN = __webpack_require__(28490); +var inherits = __webpack_require__(56698); +var Base = __webpack_require__(36677); + +var assert = utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis, + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; + }; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul), + }, + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1), + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1), + }, + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)), + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)), + }, + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + if (this.isInfinity()) + return this; + else if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate), + }, + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + + +/***/ }), + +/***/ 60480: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curves = exports; + +var hash = __webpack_require__(77952); +var curve = __webpack_require__(894); +var utils = __webpack_require__(47011); + +var assert = utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve.short(options); + else if (options.type === 'edwards') + this.curve = new curve.edwards(options); + else + this.curve = new curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve, + }); + return curve; + }, + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811', + ], +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34', + ], +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5', + ], +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f', + ], +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650', + ], +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9', + ], +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658', + ], +}); + +var pre; +try { + pre = __webpack_require__(74011); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3', + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15', + }, + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre, + ], +}); + + +/***/ }), + +/***/ 57447: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); +var HmacDRBG = __webpack_require__(32723); +var utils = __webpack_require__(47011); +var curves = __webpack_require__(60480); +var rand = __webpack_require__(15037); +var assert = utils.assert; + +var KeyPair = __webpack_require__(61200); +var Signature = __webpack_require__(28545); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(Object.prototype.hasOwnProperty.call(curves, options), + 'Unknown curve ' + options); + + options = curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray(), + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + for (;;) { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } +}; + +EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + var p; + + if (!this.curve._maxwellTrick) { + p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; + + +/***/ }), + +/***/ 61200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); +var utils = __webpack_require__(47011); +var assert = utils.assert; + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc, + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc, + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + + +/***/ }), + +/***/ 28545: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); + +var utils = __webpack_require__(47011); +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + + // Indefinite length or overflow + if (octetLen === 0 || octetLen > 4) { + return false; + } + + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; + } + + // Leading zeroes + if (val <= 0x7f) { + return false; + } + + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if (len === false) { + return false; + } + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + if (rlen === false) { + return false; + } + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (slen === false) { + return false; + } + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0) { + if (r[1] & 0x80) { + r = r.slice(1); + } else { + // Leading zeroes + return false; + } + } + if (s[0] === 0) { + if (s[1] & 0x80) { + s = s.slice(1); + } else { + // Leading zeroes + return false; + } + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 8650: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(77952); +var curves = __webpack_require__(60480); +var utils = __webpack_require__(47011); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = __webpack_require__(46661); +var Signature = __webpack_require__(90220); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + curve = curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; + + +/***/ }), + +/***/ 46661: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(47011); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; + + +/***/ }), + +/***/ 90220: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(28490); +var utils = __webpack_require__(47011); +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; + + +/***/ }), + +/***/ 74011: +/***/ ((module) => { + +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821', + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf', + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695', + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9', + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36', + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f', + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999', + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09', + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d', + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088', + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d', + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8', + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a', + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453', + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160', + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0', + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6', + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589', + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17', + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda', + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd', + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2', + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6', + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f', + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01', + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3', + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f', + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7', + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78', + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1', + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150', + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82', + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc', + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b', + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51', + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45', + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120', + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84', + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d', + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d', + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8', + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8', + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac', + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f', + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962', + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907', + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec', + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d', + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414', + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd', + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0', + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811', + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1', + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c', + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73', + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd', + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405', + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589', + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e', + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27', + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1', + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482', + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945', + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573', + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82', + ], + ], + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672', + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6', + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da', + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37', + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b', + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81', + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58', + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77', + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a', + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c', + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67', + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402', + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55', + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482', + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82', + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396', + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49', + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf', + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a', + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7', + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933', + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a', + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6', + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37', + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e', + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6', + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476', + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40', + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61', + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683', + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5', + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b', + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417', + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868', + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a', + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6', + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996', + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e', + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d', + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2', + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e', + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437', + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311', + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4', + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575', + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d', + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d', + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629', + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06', + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374', + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee', + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1', + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b', + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661', + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6', + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e', + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d', + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc', + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4', + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c', + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b', + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913', + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154', + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865', + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc', + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224', + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e', + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6', + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511', + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b', + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2', + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c', + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3', + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d', + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700', + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4', + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196', + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4', + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257', + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13', + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096', + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38', + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f', + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448', + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a', + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4', + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437', + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7', + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d', + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a', + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54', + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77', + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517', + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10', + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125', + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e', + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1', + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2', + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423', + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8', + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758', + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375', + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d', + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec', + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0', + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c', + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4', + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f', + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649', + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826', + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5', + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87', + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b', + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc', + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c', + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f', + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a', + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46', + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f', + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03', + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08', + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8', + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373', + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3', + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8', + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1', + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9', + ], + ], + }, +}; + + +/***/ }), + +/***/ 47011: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = exports; +var BN = __webpack_require__(28490); +var minAssert = __webpack_require__(43349); +var minUtils = __webpack_require__(64367); + +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; + +// Represent num in a w-NAF form +function getNAF(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + var i; + for (i = 0; i < naf.length; i += 1) { + naf[i] = 0; + } + + var ws = 1 << (w + 1); + var k = num.clone(); + + for (i = 0; i < naf.length; i++) { + var z; + var mod = k.andln(ws - 1); + if (k.isOdd()) { + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + + naf[i] = z; + k.iushrn(1); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + var m8; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + + + +/***/ }), + +/***/ 28490: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(79368).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 30655: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(70453); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ 41237: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ 69383: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 79290: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ 79538: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ 58068: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ 69675: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ 35345: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ 9723: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AF: () => (/* binding */ BatchTransactionService), +/* harmony export */ B3: () => (/* binding */ BatchBlockService), +/* harmony export */ JY: () => (/* binding */ BatchEventsService) +/* harmony export */ }); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67418); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +class BatchBlockService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getBlock(blockTag) { + return __async(this, null, function* () { + const blockObject = yield this.provider.getBlock(blockTag); + if (!blockObject) { + const errMsg = `No block for ${blockTag}`; + throw new Error(errMsg); + } + return blockObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((blocks, index) => __async(this, null, function* () { + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(20 * index); + return (() => __async(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(blocks.map((b) => this.getBlock(b))); + } catch (e) { + retries++; + err = e; + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchBlocks(blocks) { + return __async(this, null, function* () { + let blockCount = 0; + const results = []; + for (const chunks of (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .chunk */ .iv)(blocks, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .chunk */ .iv)(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + blockCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: blockCount / blocks.length, + currentIndex: blockCount, + totalIndex: blocks.length + }); + } + } + return results; + }); + } +} +class BatchTransactionService { + constructor({ + provider, + onProgress, + concurrencySize = 10, + batchSize = 10, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.batchSize = batchSize; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getTransaction(txHash) { + return __async(this, null, function* () { + const txObject = yield this.provider.getTransaction(txHash); + if (!txObject) { + const errMsg = `No transaction for ${txHash}`; + throw new Error(errMsg); + } + return txObject; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((txs, index) => __async(this, null, function* () { + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(20 * index); + return (() => __async(this, null, function* () { + let retries = 0; + let err; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield Promise.all(txs.map((tx) => this.getTransaction(tx))); + } catch (e) { + retries++; + err = e; + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(this.retryOn); + } + } + throw err; + }))(); + })); + } + getBatchTransactions(txs) { + return __async(this, null, function* () { + let txCount = 0; + const results = []; + for (const chunks of (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .chunk */ .iv)(txs, this.concurrencySize * this.batchSize)) { + const chunksResult = (yield Promise.all(this.createBatchRequest((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .chunk */ .iv)(chunks, this.batchSize)))).flat(); + results.push(...chunksResult); + txCount += chunks.length; + if (typeof this.onProgress === "function") { + this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length }); + } + } + return results; + }); + } +} +class BatchEventsService { + constructor({ + provider, + contract, + onProgress, + concurrencySize = 10, + blocksPerRequest = 2e3, + shouldRetry = true, + retryMax = 5, + retryOn = 500 + }) { + this.provider = provider; + this.contract = contract; + this.onProgress = onProgress; + this.concurrencySize = concurrencySize; + this.blocksPerRequest = blocksPerRequest; + this.shouldRetry = shouldRetry; + this.retryMax = retryMax; + this.retryOn = retryOn; + } + getPastEvents(_0) { + return __async(this, arguments, function* ({ fromBlock, toBlock, type }) { + let err; + let retries = 0; + while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { + try { + return yield this.contract.queryFilter(type, fromBlock, toBlock); + } catch (e) { + err = e; + retries++; + if (e.message.includes("after last accepted block")) { + const acceptedBlock = parseInt(e.message.split("after last accepted block ")[1]); + toBlock = acceptedBlock; + } + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(this.retryOn); + } + } + throw err; + }); + } + createBatchRequest(batchArray) { + return batchArray.map((event, index) => __async(this, null, function* () { + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(20 * index); + return this.getPastEvents(event); + })); + } + getBatchEvents(_0) { + return __async(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + const eventsToSync = []; + for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) { + const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1; + eventsToSync.push({ fromBlock: i, toBlock: j, type }); + } + const events = []; + const eventChunk = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .chunk */ .iv)(eventsToSync, this.concurrencySize); + let chunkCount = 0; + for (const chunk2 of eventChunk) { + chunkCount++; + const fetchedEvents = (yield Promise.all(this.createBatchRequest(chunk2))).flat(); + events.push(...fetchedEvents); + if (typeof this.onProgress === "function") { + this.onProgress({ + percentage: chunkCount / eventChunk.length, + type, + fromBlock: chunk2[0].fromBlock, + toBlock: chunk2[chunk2.length - 1].toBlock, + count: fetchedEvents.length + }); + } + } + return events; + }); + } +} + + +/***/ }), + +/***/ 11489: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + RG: () => (/* binding */ download), + hn: () => (/* binding */ existsAsync), + sw: () => (/* binding */ loadCachedEvents), + rx: () => (/* binding */ loadSavedEvents), + jj: () => (/* binding */ saveUserFile), + fY: () => (/* binding */ unzipAsync), + a8: () => (/* binding */ zipAsync) +}); + +// EXTERNAL MODULE: path (ignored) +var path_ignored_ = __webpack_require__(21628); +var path_ignored_default = /*#__PURE__*/__webpack_require__.n(path_ignored_); +// EXTERNAL MODULE: fs/promises (ignored) +var promises_ignored_ = __webpack_require__(26840); +;// CONCATENATED MODULE: ./node_modules/fflate/esm/browser.js +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var ch2 = {}; +var wk = (function (c, id, msg, transfer, cb) { + var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([ + c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})' + ], { type: 'text/javascript' })))); + w.onmessage = function (e) { + var d = e.data, ed = d.$e$; + if (ed) { + var err = new Error(ed[0]); + err['code'] = ed[1]; + err.stack = ed[2]; + cb(err, null); + } + else + cb(null, d); + }; + w.postMessage(msg, transfer); + return w; +}); + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +var FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data.length) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + w.postMessage([d, t = f], [d.buffer]); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function () { w.postMessage([]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + */ + Deflate.prototype.flush = function () { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + }; + return Deflate; +}()))); + +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()))); + +function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()))); + +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()))); + +function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + */ + Gzip.prototype.flush = function () { + Deflate.prototype.flush.call(this); + }; + return Gzip; +}()))); + +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()))); + +function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + // process concatenated GZIP + if (this.s.f && !this.s.l && !final) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + }; + return Gunzip; +}()))); + +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()))); + +function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + */ + Zlib.prototype.flush = function () { + Deflate.prototype.flush.call(this); + }; + return Zlib; +}()))); + +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()))); + +function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()))); + +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()))); + +function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// Default algorithm for compression (used because having a known output size allows faster decompression) + + +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()))); + +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()))); + +function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (val instanceof u8) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()))); + +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()))); + +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20); + var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off]; +}; +// read zip64 extra field +var z64e = function (d, b) { + for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)) + ; + return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()))); + +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()))); + +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()))); + +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()))); + +function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (data, final) { + this.ondata(null, data, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()))); + +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (data, final) { + try { + this.i.push(data, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()))); + +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (data, final) { + if (this.i.terminate) + data = slc(data, 0); + this.i.push(data, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()))); + +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var _a; + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + if (sc_1 == 4294967295) { + _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1]; + } + else if (dd) + sc_1 = -1; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()))); + +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = o == 4294967295 || c == 65535; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = o == 4294967295 || c == 65535; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} + +;// CONCATENATED MODULE: ./src/data.ts +/* provided dependency */ var console = __webpack_require__(96763); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + +function existsAsync(fileOrDir) { + return __async(this, null, function* () { + try { + yield (0,promises_ignored_.stat)(fileOrDir); + return true; + } catch (e) { + return false; + } + }); +} +function zipAsync(file) { + return new Promise((res, rej) => { + zip(file, { mtime: /* @__PURE__ */ new Date("1/1/1980") }, (err, data) => { + if (err) { + rej(err); + return; + } + res(data); + }); + }); +} +function unzipAsync(data) { + return new Promise((res, rej) => { + unzip(data, {}, (err, data2) => { + if (err) { + rej(err); + return; + } + res(data2); + }); + }); +} +function saveUserFile(_0) { + return __async(this, arguments, function* ({ + fileName, + userDirectory, + dataString + }) { + fileName = fileName.toLowerCase(); + const filePath = path_ignored_default().join(userDirectory, fileName); + const payload = yield zipAsync({ + [fileName]: new TextEncoder().encode(dataString) + }); + if (!(yield existsAsync(userDirectory))) { + yield (0,promises_ignored_.mkdir)(userDirectory, { recursive: true }); + } + yield (0,promises_ignored_.writeFile)(filePath + ".zip", payload); + yield (0,promises_ignored_.writeFile)(filePath, dataString); + }); +} +function loadSavedEvents(_0) { + return __async(this, arguments, function* ({ + name, + userDirectory, + deployedBlock + }) { + const filePath = path_ignored_default().join(userDirectory, `${name}.json`.toLowerCase()); + if (!(yield existsAsync(filePath))) { + return { + events: [], + lastBlock: null + }; + } + try { + const events = JSON.parse(yield (0,promises_ignored_.readFile)(filePath, { encoding: "utf8" })); + return { + events, + lastBlock: events && events.length ? events[events.length - 1].blockNumber : deployedBlock + }; + } catch (err) { + console.log("Method loadSavedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} +function download(_0) { + return __async(this, arguments, function* ({ name, cacheDirectory }) { + const fileName = `${name}.json`.toLowerCase(); + const zipName = `${fileName}.zip`; + const zipPath = path_ignored_default().join(cacheDirectory, zipName); + const data = yield (0,promises_ignored_.readFile)(zipPath); + const { [fileName]: content } = yield unzipAsync(data); + return new TextDecoder().decode(content); + }); +} +function loadCachedEvents(_0) { + return __async(this, arguments, function* ({ + name, + cacheDirectory, + deployedBlock + }) { + try { + const module = yield download({ cacheDirectory, name }); + if (module) { + const events = JSON.parse(module); + const lastBlock = events && events.length ? events[events.length - 1].blockNumber : deployedBlock; + return { + events, + lastBlock + }; + } + return { + events: [], + lastBlock: deployedBlock + }; + } catch (err) { + console.log("Method loadCachedEvents has error"); + console.log(err); + return { + events: [], + lastBlock: deployedBlock + }; + } + }); +} + + +/***/ }), + +/***/ 7240: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Hr: () => (/* binding */ createDeposit), +/* harmony export */ dA: () => (/* binding */ Deposit), +/* harmony export */ qO: () => (/* binding */ Invoice) +/* harmony export */ }); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67418); +/* harmony import */ var _pedersen__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85111); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + +function createDeposit(_0) { + return __async(this, arguments, function* ({ nullifier, secret }) { + const preimage = new Uint8Array([...(0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leInt2Buff */ .EI)(nullifier), ...(0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leInt2Buff */ .EI)(secret)]); + const noteHex = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .toFixedHex */ .$W)((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .bytesToBN */ .Ju)(preimage), 62); + const commitment = BigInt(yield (0,_pedersen__WEBPACK_IMPORTED_MODULE_1__/* .buffPedersenHash */ .UB)(preimage)); + const commitmentHex = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .toFixedHex */ .$W)(commitment); + const nullifierHash = BigInt(yield (0,_pedersen__WEBPACK_IMPORTED_MODULE_1__/* .buffPedersenHash */ .UB)((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leInt2Buff */ .EI)(nullifier))); + const nullifierHex = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .toFixedHex */ .$W)(nullifierHash); + return { + preimage, + noteHex, + commitment, + commitmentHex, + nullifierHash, + nullifierHex + }; + }); +} +class Deposit { + constructor({ + currency, + amount, + netId, + nullifier, + secret, + note, + noteHex, + invoice, + commitmentHex, + nullifierHex + }) { + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.nullifier = nullifier; + this.secret = secret; + this.note = note; + this.noteHex = noteHex; + this.invoice = invoice; + this.commitmentHex = commitmentHex; + this.nullifierHex = nullifierHex; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + nullifier: this.nullifier, + secret: this.secret, + note: this.note, + noteHex: this.noteHex, + invoice: this.invoice, + commitmentHex: this.commitmentHex, + nullifierHex: this.nullifierHex + }, + null, + 2 + ); + } + static createNote(_0) { + return __async(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { + if (!nullifier) { + nullifier = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .rBigInt */ .ib)(31); + } + if (!secret) { + secret = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .rBigInt */ .ib)(31); + } + const depositObject = yield createDeposit({ + nullifier, + secret + }); + const newDeposit = new Deposit({ + currency: currency.toLowerCase(), + amount, + netId, + note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`, + noteHex: depositObject.noteHex, + invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } + static parseNote(noteString) { + return __async(this, null, function* () { + const noteRegex = new RegExp("tornado-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{124})", "g"); + const match = noteRegex.exec(noteString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + const bytes = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .bnToBytes */ .jm)("0x" + matchGroup.note); + const nullifier = BigInt((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leBuff2Int */ .ae)(bytes.slice(0, 31)).toString()); + const secret = BigInt((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leBuff2Int */ .ae)(bytes.slice(31, 62)).toString()); + const depositObject = yield createDeposit({ nullifier, secret }); + const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`; + const newDeposit = new Deposit({ + currency, + amount, + netId, + note: noteString, + noteHex: depositObject.noteHex, + invoice, + nullifier, + secret, + commitmentHex: depositObject.commitmentHex, + nullifierHex: depositObject.nullifierHex + }); + return newDeposit; + }); + } +} +class Invoice { + constructor(invoiceString) { + const invoiceRegex = new RegExp("tornadoInvoice-(?\\w+)-(?[\\d.]+)-(?\\d+)-0x(?[0-9a-fA-F]{64})", "g"); + const match = invoiceRegex.exec(invoiceString); + if (!match) { + throw new Error("The note has invalid format"); + } + const matchGroup = match == null ? void 0 : match.groups; + const currency = matchGroup.currency.toLowerCase(); + const amount = matchGroup.amount; + const netId = Number(matchGroup.netId); + this.currency = currency; + this.amount = amount; + this.netId = netId; + this.commitment = "0x" + matchGroup.commitment; + this.invoice = invoiceString; + } + toString() { + return JSON.stringify( + { + currency: this.currency, + amount: this.amount, + netId: this.netId, + commitment: this.commitment, + invoice: this.invoice + }, + null, + 2 + ); + } +} + + +/***/ }), + +/***/ 33298: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ad: () => (/* binding */ NoteAccount), +/* harmony export */ Fr: () => (/* binding */ packEncryptedMessage), +/* harmony export */ ol: () => (/* binding */ unpackEncryptedMessage) +/* harmony export */ }); +/* harmony import */ var _metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51594); +/* harmony import */ var _metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20415); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30031); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67418); + + + + +function packEncryptedMessage({ nonce, ephemPublicKey, ciphertext }) { + const nonceBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .toFixedHex */ .$W)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .base64ToBytes */ .Kp)(nonce)), 24); + const ephemPublicKeyBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .toFixedHex */ .$W)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .base64ToBytes */ .Kp)(ephemPublicKey)), 32); + const ciphertextBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .base64ToBytes */ .Kp)(ciphertext)); + const messageBuff = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .concatBytes */ .Id)((0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .hexToBytes */ .aT)(nonceBuf), (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .hexToBytes */ .aT)(ephemPublicKeyBuf), (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .hexToBytes */ .aT)(ciphertextBuf)); + return (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)(messageBuff); +} +function unpackEncryptedMessage(encryptedMessage) { + const messageBuff = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .hexToBytes */ .aT)(encryptedMessage); + const nonceBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToBase64 */ ["if"])(messageBuff.slice(0, 24)); + const ephemPublicKeyBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToBase64 */ ["if"])(messageBuff.slice(24, 56)); + const ciphertextBuf = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToBase64 */ ["if"])(messageBuff.slice(56)); + return { + messageBuff: (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)(messageBuff), + version: "x25519-xsalsa20-poly1305", + nonce: nonceBuf, + ephemPublicKey: ephemPublicKeyBuf, + ciphertext: ciphertextBuf + }; +} +class NoteAccount { + constructor({ netId, blockNumber, recoveryKey, Echoer: Echoer2 }) { + if (!recoveryKey) { + recoveryKey = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .bytesToHex */ .My)(_utils__WEBPACK_IMPORTED_MODULE_1__/* .crypto */ .Et.getRandomValues(new Uint8Array(32))).slice(2); + } + this.netId = Math.floor(Number(netId)); + this.blockNumber = blockNumber; + this.recoveryKey = recoveryKey; + this.recoveryAddress = (0,ethers__WEBPACK_IMPORTED_MODULE_2__/* .computeAddress */ .K)("0x" + recoveryKey); + this.recoveryPublicKey = (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.getEncryptionPublicKey)(recoveryKey); + this.Echoer = Echoer2; + } + /** + * Intends to mock eth_getEncryptionPublicKey behavior from MetaMask + * In order to make the recoveryKey retrival from Echoer possible from the bare private key + */ + static getWalletPublicKey(wallet) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + return (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.getEncryptionPublicKey)(privateKey); + } + // This function intends to provide an encrypted value of recoveryKey for an on-chain Echoer backup purpose + // Thus, the pubKey should be derived by a Wallet instance or from Web3 wallets + // pubKey: base64 encoded 32 bytes key from https://docs.metamask.io/wallet/reference/eth_getencryptionpublickey/ + getEncryptedAccount(walletPublicKey) { + const encryptedData = (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.encrypt)({ + publicKey: walletPublicKey, + data: this.recoveryKey, + version: "x25519-xsalsa20-poly1305" + }); + const data = packEncryptedMessage(encryptedData); + return { + // Use this later to save hexPrivateKey generated with + // Buffer.from(JSON.stringify(encryptedData)).toString('hex') + // As we don't use buffer with this library we should leave UI to do the rest + encryptedData, + // Data that could be used as an echo(data) params + data + }; + } + /** + * Decrypt Echoer backuped note encryption account with private keys + */ + decryptAccountsWithWallet(wallet, events) { + let { privateKey } = wallet; + if (privateKey.startsWith("0x")) { + privateKey = privateKey.replace("0x", ""); + } + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedAccount); + const recoveryKey = (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.decrypt)({ + encryptedData: unpackedMessage, + privateKey + }); + decryptedEvents.push( + new NoteAccount({ + netId: this.netId, + blockNumber: event.blockNumber, + recoveryKey, + Echoer: this.Echoer + }) + ); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + decryptNotes(events) { + const decryptedEvents = []; + for (const event of events) { + try { + const unpackedMessage = unpackEncryptedMessage(event.encryptedNote); + const [address, noteHex] = (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.decrypt)({ + encryptedData: unpackedMessage, + privateKey: this.recoveryKey + }).split("-"); + decryptedEvents.push({ + blockNumber: event.blockNumber, + address: (0,ethers__WEBPACK_IMPORTED_MODULE_3__/* .getAddress */ .b)(address), + noteHex + }); + } catch (e) { + continue; + } + } + return decryptedEvents; + } + encryptNote({ address, noteHex }) { + const encryptedData = (0,_metamask_eth_sig_util__WEBPACK_IMPORTED_MODULE_0__.encrypt)({ + publicKey: this.recoveryPublicKey, + data: `${address}-${noteHex}`, + version: "x25519-xsalsa20-poly1305" + }); + return packEncryptedMessage(encryptedData); + } +} + + +/***/ }), + +/***/ 71304: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ GS: () => (/* binding */ BaseEchoService), +/* harmony export */ JJ: () => (/* binding */ BaseGovernanceService), +/* harmony export */ Lx: () => (/* binding */ DEPOSIT), +/* harmony export */ O_: () => (/* binding */ BaseEncryptedNotesService), +/* harmony export */ cE: () => (/* binding */ BaseRegistryService), +/* harmony export */ oW: () => (/* binding */ WITHDRAWAL), +/* harmony export */ qD: () => (/* binding */ BaseDepositsService), +/* harmony export */ uw: () => (/* binding */ BaseEventsService) +/* harmony export */ }); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30031); +/* harmony import */ var _graphql__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52049); +/* harmony import */ var _batch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9723); +/* provided dependency */ var console = __webpack_require__(96763); + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + +const DEPOSIT = "deposit"; +const WITHDRAWAL = "withdrawal"; +class BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + contract, + type = "", + deployedBlock = 0, + fetchDataOptions: fetchDataOptions2 + }) { + this.netId = netId; + this.provider = provider; + this.graphApi = graphApi; + this.subgraphName = subgraphName; + this.fetchDataOptions = fetchDataOptions2; + this.contract = contract; + this.type = type; + this.deployedBlock = deployedBlock; + this.batchEventsService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchEventsService */ .JY({ + provider, + contract, + onProgress: this.updateEventProgress + }); + } + getInstanceName() { + return ""; + } + getType() { + return this.type || ""; + } + getGraphMethod() { + return ""; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + updateEventProgress({ percentage, type, fromBlock, toBlock, count }) { + } + updateBlockProgress({ percentage, currentIndex, totalIndex }) { + } + updateTransactionProgress({ percentage, currentIndex, totalIndex }) { + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + } + /* eslint-enable @typescript-eslint/no-unused-vars */ + formatEvents(events) { + return __async(this, null, function* () { + return yield new Promise((resolve) => resolve(events)); + }); + } + /** + * Get saved or cached events + */ + getEventsFromDB() { + return __async(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + return { + events: [], + lastBlock: null + }; + }); + } + getSavedEvents() { + return __async(this, null, function* () { + let cachedEvents = yield this.getEventsFromDB(); + if (!cachedEvents || !cachedEvents.events.length) { + cachedEvents = yield this.getEventsFromCache(); + } + return cachedEvents; + }); + } + /** + * Get latest events + */ + getEventsFromGraph(_0) { + return __async(this, arguments, function* ({ + fromBlock, + methodName = "" + }) { + if (!this.graphApi || !this.subgraphName) { + return { + events: [], + lastBlock: fromBlock + }; + } + const { events, lastSyncBlock } = yield _graphql__WEBPACK_IMPORTED_MODULE_0__[methodName || this.getGraphMethod()](__spreadValues({ + fromBlock + }, this.getGraphParams())); + return { + events, + lastBlock: lastSyncBlock + }; + }); + } + getEventsFromRpc(_0) { + return __async(this, arguments, function* ({ + fromBlock, + toBlock + }) { + try { + if (!toBlock) { + toBlock = yield this.provider.getBlockNumber(); + } + if (fromBlock >= toBlock) { + return { + events: [], + lastBlock: toBlock + }; + } + this.updateEventProgress({ percentage: 0, type: this.getType() }); + const events = yield this.formatEvents( + yield this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() }) + ); + if (!events.length) { + return { + events, + lastBlock: toBlock + }; + } + return { + events, + lastBlock: toBlock + }; + } catch (err) { + console.log(err); + return { + events: [], + lastBlock: fromBlock + }; + } + }); + } + getLatestEvents(_0) { + return __async(this, arguments, function* ({ fromBlock }) { + const allEvents = []; + const graphEvents = yield this.getEventsFromGraph({ fromBlock }); + const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock; + const rpcEvents = yield this.getEventsFromRpc({ fromBlock: lastSyncBlock }); + allEvents.push(...graphEvents.events); + allEvents.push(...rpcEvents.events); + const lastBlock = rpcEvents ? rpcEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : fromBlock; + return { + events: allEvents, + lastBlock + }; + }); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validateEvents({ events, lastBlock }) { + } + /** + * Handle saving events + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + }); + } + /** + * Trigger saving and receiving latest events + */ + updateEvents() { + return __async(this, null, function* () { + const savedEvents = yield this.getSavedEvents(); + let fromBlock = this.deployedBlock; + if (savedEvents && savedEvents.lastBlock) { + fromBlock = savedEvents.lastBlock + 1; + } + const newEvents = yield this.getLatestEvents({ fromBlock }); + const eventSet = /* @__PURE__ */ new Set(); + let allEvents = []; + allEvents.push(...savedEvents.events); + allEvents.push(...newEvents.events); + allEvents = allEvents.sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }).filter(({ transactionHash, logIndex }) => { + const eventKey = `${transactionHash}_${logIndex}`; + const hasEvent = eventSet.has(eventKey); + eventSet.add(eventKey); + return !hasEvent; + }); + const lastBlock = newEvents ? newEvents.lastBlock : allEvents[allEvents.length - 1] ? allEvents[allEvents.length - 1].blockNumber : null; + this.validateEvents({ events: allEvents, lastBlock }); + yield this.saveEvents({ events: allEvents, lastBlock }); + return { + events: allEvents, + lastBlock + }; + }); + } +} +class BaseDepositsService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Tornado, type, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.amount = amount; + this.currency = currency; + this.batchTransactionService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchTransactionService */ .AF({ + provider, + onProgress: this.updateTransactionProgress + }); + this.batchBlockService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchBlockService */ .B3({ + provider, + onProgress: this.updateBlockProgress + }); + } + getInstanceName() { + return `${this.getType().toLowerCase()}s_${this.netId}_${this.currency}_${this.amount}`; + } + getGraphMethod() { + return `getAll${this.getType()}s`; + } + getGraphParams() { + return { + graphApi: this.graphApi || "", + subgraphName: this.subgraphName || "", + amount: this.amount, + currency: this.currency, + fetchDataOptions: this.fetchDataOptions, + onProgress: this.updateGraphProgress + }; + } + formatEvents(events) { + return __async(this, null, function* () { + const type = this.getType().toLowerCase(); + if (type === DEPOSIT) { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { commitment, leafIndex, timestamp } = args; + return { + blockNumber, + logIndex, + transactionHash, + commitment, + leafIndex: Number(leafIndex), + timestamp: Number(timestamp) + }; + }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(formattedEvents.map(({ transactionHash }) => transactionHash)) + ]); + return formattedEvents.map((event) => { + const { from } = txs.find(({ hash }) => hash === event.transactionHash); + return __spreadProps(__spreadValues({}, event), { + from + }); + }); + } else { + const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { nullifierHash, to, fee } = args; + return { + blockNumber, + logIndex, + transactionHash, + nullifierHash: String(nullifierHash), + to: (0,ethers__WEBPACK_IMPORTED_MODULE_2__/* .getAddress */ .b)(to), + fee: String(fee) + }; + }); + const blocks = yield this.batchBlockService.getBatchBlocks([ + ...new Set(formattedEvents.map(({ blockNumber }) => blockNumber)) + ]); + return formattedEvents.map((event) => { + const { timestamp } = blocks.find(({ number }) => number === event.blockNumber); + return __spreadProps(__spreadValues({}, event), { + timestamp + }); + }); + } + }); + } + validateEvents({ events }) { + if (events.length && this.getType().toLowerCase() === DEPOSIT) { + const lastEvent = events[events.length - 1]; + if (lastEvent.leafIndex !== events.length - 1) { + const errMsg = `Deposit events invalid wants ${events.length - 1} leafIndex have ${lastEvent.leafIndex}`; + throw new Error(errMsg); + } + } + } +} +class BaseEchoService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Echoer, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `echo_${this.netId}`; + } + getType() { + return "Echo"; + } + getGraphMethod() { + return "getAllGraphEchoEvents"; + } + formatEvents(events) { + return __async(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { who, data } = args; + if (who && data) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps(__spreadValues({}, eventObjects), { + address: who, + encryptedAccount: data + }); + } + }).filter((e) => e); + }); + } + getEventsFromGraph(_0) { + return __async(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseEchoService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseEncryptedNotesService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Router, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `encrypted_notes_${this.netId}`; + } + getType() { + return "EncryptedNote"; + } + getGraphMethod() { + return "getAllEncryptedNotes"; + } + formatEvents(events) { + return __async(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const { encryptedNote } = args; + if (encryptedNote) { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps(__spreadValues({}, eventObjects), { + encryptedNote + }); + } + }).filter((e) => e); + }); + } +} +class BaseGovernanceService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: Governance, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + this.batchTransactionService = new _batch__WEBPACK_IMPORTED_MODULE_1__/* .BatchTransactionService */ .AF({ + provider, + onProgress: this.updateTransactionProgress + }); + } + getInstanceName() { + return `governance_${this.netId}`; + } + getType() { + return "*"; + } + getGraphMethod() { + return "getAllGovernanceEvents"; + } + formatEvents(events) { + return __async(this, null, function* () { + const proposalEvents = []; + const votedEvents = []; + const delegatedEvents = []; + const undelegatedEvents = []; + events.forEach(({ blockNumber, index: logIndex, transactionHash, args, eventName: event }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash, + event + }; + if (event === "ProposalCreated") { + const { id, proposer, target, startTime, endTime, description } = args; + proposalEvents.push(__spreadProps(__spreadValues({}, eventObjects), { + id: Number(id), + proposer, + target, + startTime: Number(startTime), + endTime: Number(endTime), + description + })); + } + if (event === "Voted") { + const { proposalId, voter, support, votes } = args; + votedEvents.push(__spreadProps(__spreadValues({}, eventObjects), { + proposalId: Number(proposalId), + voter, + support, + votes, + from: "", + input: "" + })); + } + if (event === "Delegated") { + const { account, to: delegateTo } = args; + delegatedEvents.push(__spreadProps(__spreadValues({}, eventObjects), { + account, + delegateTo + })); + } + if (event === "Undelegated") { + const { account, from: delegateFrom } = args; + undelegatedEvents.push(__spreadProps(__spreadValues({}, eventObjects), { + account, + delegateFrom + })); + } + }); + if (votedEvents.length) { + this.updateTransactionProgress({ percentage: 0 }); + const txs = yield this.batchTransactionService.getBatchTransactions([ + ...new Set(votedEvents.map(({ transactionHash }) => transactionHash)) + ]); + votedEvents.forEach((event, index) => { + let { data: input, from } = txs.find((t) => t.hash === event.transactionHash); + if (!input || input.length > 2048) { + input = ""; + } + votedEvents[index].from = from; + votedEvents[index].input = input; + }); + } + return [...proposalEvents, ...votedEvents, ...delegatedEvents, ...undelegatedEvents]; + }); + } + getEventsFromGraph(_0) { + return __async(this, arguments, function* ({ fromBlock }) { + if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { + return { + events: [], + lastBlock: fromBlock + }; + } + return __superGet(BaseGovernanceService.prototype, this, "getEventsFromGraph").call(this, { fromBlock }); + }); + } +} +class BaseRegistryService extends BaseEventsService { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions: fetchDataOptions2 + }) { + super({ netId, provider, graphApi, subgraphName, contract: RelayerRegistry, deployedBlock, fetchDataOptions: fetchDataOptions2 }); + } + getInstanceName() { + return `registered_${this.netId}`; + } + // Name of type used for events + getType() { + return "RelayerRegistered"; + } + // Name of method used for graph + getGraphMethod() { + return "getAllRegisters"; + } + formatEvents(events) { + return __async(this, null, function* () { + return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { + const eventObjects = { + blockNumber, + logIndex, + transactionHash + }; + return __spreadProps(__spreadValues({}, eventObjects), { + ensName: args.ensName, + relayerAddress: args.relayerAddress + }); + }); + }); + } + fetchRelayers() { + return __async(this, null, function* () { + return (yield this.updateEvents()).events; + }); + } +} + + +/***/ }), + +/***/ 94513: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ BaseDepositsService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.qD), +/* harmony export */ BaseEchoService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.GS), +/* harmony export */ BaseEncryptedNotesService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.O_), +/* harmony export */ BaseEventsService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.uw), +/* harmony export */ BaseGovernanceService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.JJ), +/* harmony export */ BaseRegistryService: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.cE), +/* harmony export */ DEPOSIT: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.Lx), +/* harmony export */ NodeDepositsService: () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_2__.fD), +/* harmony export */ NodeEchoService: () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_2__.Rl), +/* harmony export */ NodeEncryptedNotesService: () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_2__.l5), +/* harmony export */ NodeGovernanceService: () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_2__.Om), +/* harmony export */ NodeRegistryService: () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_2__.b5), +/* harmony export */ WITHDRAWAL: () => (/* reexport safe */ _base__WEBPACK_IMPORTED_MODULE_1__.oW) +/* harmony export */ }); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(61060); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_types__WEBPACK_IMPORTED_MODULE_0__); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _types__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== "default") __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _types__WEBPACK_IMPORTED_MODULE_0__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(71304); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82737); + + + + + + +/***/ }), + +/***/ 82737: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Om: () => (/* binding */ NodeGovernanceService), +/* harmony export */ Rl: () => (/* binding */ NodeEchoService), +/* harmony export */ b5: () => (/* binding */ NodeRegistryService), +/* harmony export */ fD: () => (/* binding */ NodeDepositsService), +/* harmony export */ l5: () => (/* binding */ NodeEncryptedNotesService) +/* harmony export */ }); +/* harmony import */ var cli_table3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(29530); +/* harmony import */ var cli_table3__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cli_table3__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(95093); +/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11489); +/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(71304); +/* provided dependency */ var console = __webpack_require__(96763); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + +class NodeDepositsService extends _base__WEBPACK_IMPORTED_MODULE_3__/* .BaseDepositsService */ .qD { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Tornado, + type, + amount, + currency, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} deposit txs of ${totalIndex}`); + } + } + updateBlockProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} withdrawal blocks of ${totalIndex}`); + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async(this, null, function* () { + if (!this.userDirectory) { + console.log( + "Updating events for", + this.amount, + this.currency.toUpperCase(), + `${this.getType().toLowerCase()}s +` + ); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadSavedEvents */ .rx)({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log("Updating events for", this.amount, this.currency.toUpperCase(), `${this.getType().toLowerCase()}s +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadCachedEvents */ .sw)({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new (cli_table3__WEBPACK_IMPORTED_MODULE_0___default())(); + eventTable.push( + [{ colSpan: 2, content: `${this.getType()}s`, hAlign: "center" }], + ["Instance", `${this.netId} chain ${this.amount} ${this.currency.toUpperCase()}`], + ["Anonymity set", `${events.length} equal user ${this.getType().toLowerCase()}s`], + [{ colSpan: 2, content: `Latest ${this.getType().toLowerCase()}s` }], + ...events.slice(events.length - 10).reverse().map(({ timestamp }, index) => { + const eventIndex = events.length - index; + const eventTime = moment__WEBPACK_IMPORTED_MODULE_1___default().unix(timestamp).fromNow(); + return [eventIndex, eventTime]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .saveUserFile */ .jj)({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEchoService extends _base__WEBPACK_IMPORTED_MODULE_3__/* .BaseEchoService */ .GS { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Echoer, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadSavedEvents */ .rx)({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain echo events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadCachedEvents */ .sw)({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new (cli_table3__WEBPACK_IMPORTED_MODULE_0___default())(); + eventTable.push( + [{ colSpan: 2, content: "Echo Accounts", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .saveUserFile */ .jj)({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeEncryptedNotesService extends _base__WEBPACK_IMPORTED_MODULE_3__/* .BaseEncryptedNotesService */ .O_ { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Router, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadSavedEvents */ .rx)({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain encrypted events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadCachedEvents */ .sw)({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new (cli_table3__WEBPACK_IMPORTED_MODULE_0___default())(); + eventTable.push( + [{ colSpan: 2, content: "Encrypted Notes", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .saveUserFile */ .jj)({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeGovernanceService extends _base__WEBPACK_IMPORTED_MODULE_3__/* .BaseGovernanceService */ .JJ { + constructor({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + Governance, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + updateTransactionProgress({ currentIndex, totalIndex }) { + if (totalIndex) { + console.log(`Fetched ${currentIndex} governance txs of ${totalIndex}`); + } + } + getEventsFromDB() { + return __async(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadSavedEvents */ .rx)({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain governance events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadCachedEvents */ .sw)({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new (cli_table3__WEBPACK_IMPORTED_MODULE_0___default())(); + eventTable.push( + [{ colSpan: 2, content: "Governance Events", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .saveUserFile */ .jj)({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} +class NodeRegistryService extends _base__WEBPACK_IMPORTED_MODULE_3__/* .BaseRegistryService */ .cE { + constructor({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions, + cacheDirectory, + userDirectory + }) { + super({ + netId, + provider, + graphApi, + subgraphName, + RelayerRegistry, + deployedBlock, + fetchDataOptions + }); + this.cacheDirectory = cacheDirectory; + this.userDirectory = userDirectory; + } + updateEventProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from ${fromBlock} to ${toBlock} +`); + } + } + } + updateGraphProgress({ type, fromBlock, toBlock, count }) { + if (toBlock) { + console.log(`fromBlock - ${fromBlock}`); + console.log(`toBlock - ${toBlock}`); + if (count) { + console.log(`downloaded ${type} events from graph node count - ${count}`); + console.log("____________________________________________"); + console.log(`Fetched ${type} events from graph node ${fromBlock} to ${toBlock} +`); + } + } + } + getEventsFromDB() { + return __async(this, null, function* () { + if (!this.userDirectory) { + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${0}`); + console.log(`savedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const savedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadSavedEvents */ .rx)({ + name: this.getInstanceName(), + userDirectory: this.userDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`Updating events for ${this.netId} chain registry events +`); + console.log(`savedEvents count - ${savedEvents.events.length}`); + console.log(`savedEvents lastBlock - ${savedEvents.lastBlock} +`); + return savedEvents; + }); + } + getEventsFromCache() { + return __async(this, null, function* () { + if (!this.cacheDirectory) { + console.log(`cachedEvents count - ${0}`); + console.log(`cachedEvents lastBlock - ${this.deployedBlock} +`); + return { + events: [], + lastBlock: this.deployedBlock + }; + } + const cachedEvents = yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .loadCachedEvents */ .sw)({ + name: this.getInstanceName(), + cacheDirectory: this.cacheDirectory, + deployedBlock: this.deployedBlock + }); + console.log(`cachedEvents count - ${cachedEvents.events.length}`); + console.log(`cachedEvents lastBlock - ${cachedEvents.lastBlock} +`); + return cachedEvents; + }); + } + saveEvents(_0) { + return __async(this, arguments, function* ({ events, lastBlock }) { + const instanceName = this.getInstanceName(); + console.log("\ntotalEvents count - ", events.length); + console.log( + `totalEvents lastBlock - ${events[events.length - 1] ? events[events.length - 1].blockNumber : lastBlock} +` + ); + const eventTable = new (cli_table3__WEBPACK_IMPORTED_MODULE_0___default())(); + eventTable.push( + [{ colSpan: 2, content: "Registered Relayers", hAlign: "center" }], + ["Network", `${this.netId} chain`], + ["Events", `${events.length} events`], + [{ colSpan: 2, content: "Latest events" }], + ...events.slice(events.length - 10).reverse().map(({ blockNumber }, index) => { + const eventIndex = events.length - index; + return [eventIndex, blockNumber]; + }) + ); + console.log(eventTable.toString() + "\n"); + if (this.userDirectory) { + yield (0,_data__WEBPACK_IMPORTED_MODULE_2__/* .saveUserFile */ .jj)({ + fileName: instanceName + ".json", + userDirectory: this.userDirectory, + dataString: JSON.stringify(events, null, 2) + "\n" + }); + } + }); + } +} + + +/***/ }), + +/***/ 61060: +/***/ (() => { + +"use strict"; + + + +/***/ }), + +/***/ 37182: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ N: () => (/* binding */ convertETHToTokenAmount), +/* harmony export */ o: () => (/* binding */ TornadoFeeOracle) +/* harmony export */ }); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99770); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(79453); + + +const DUMMY_ADDRESS = "0x1111111111111111111111111111111111111111"; +const DUMMY_NONCE = "0x1111111111111111111111111111111111111111111111111111111111111111"; +const DUMMY_WITHDRAW_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; +function convertETHToTokenAmount(amountInWei, tokenPriceInWei, tokenDecimals = 18) { + const tokenDecimalsMultiplier = BigInt(10 ** Number(tokenDecimals)); + return BigInt(amountInWei) * tokenDecimalsMultiplier / BigInt(tokenPriceInWei); +} +class TornadoFeeOracle { + constructor(ovmGasPriceOracle) { + if (ovmGasPriceOracle) { + this.ovmGasPriceOracle = ovmGasPriceOracle; + } + } + /** + * Calculate L1 fee for op-stack chains + * + * This is required since relayers would pay the full transaction fees for users + */ + fetchL1OptimismFee(tx) { + if (!this.ovmGasPriceOracle) { + return new Promise((resolve) => resolve(BigInt(0))); + } + if (!tx) { + tx = { + type: 0, + gasLimit: 1e6, + nonce: Number(DUMMY_NONCE), + data: DUMMY_WITHDRAW_DATA, + gasPrice: (0,ethers__WEBPACK_IMPORTED_MODULE_0__/* .parseUnits */ .XS)("1", "gwei"), + from: DUMMY_ADDRESS, + to: DUMMY_ADDRESS + }; + } + return this.ovmGasPriceOracle.getL1Fee.staticCall(ethers__WEBPACK_IMPORTED_MODULE_1__/* .Transaction */ .Z.from(tx).unsignedSerialized); + } + /** + * We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal + * So we default with 1M gas which is enough for two or three swaps + * Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI + */ + defaultEthRefund(gasPrice, gasLimit) { + return (gasPrice ? BigInt(gasPrice) : (0,ethers__WEBPACK_IMPORTED_MODULE_0__/* .parseUnits */ .XS)("30", "gwei")) * BigInt(gasLimit || 1e6); + } + /** + * Calculates token amount for required ethRefund purchases required to calculate fees + */ + calculateTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals) { + return convertETHToTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals); + } + /** + * Warning: For tokens you need to check if the fees are above denomination + * (Usually happens for small denomination pool or if the gas price is high) + */ + calculateRelayerFee({ + gasPrice, + gasLimit = 6e5, + l1Fee = 0, + denomination, + ethRefund = BigInt(0), + tokenPriceInWei, + tokenDecimals = 18, + relayerFeePercent = 0.33, + isEth = true, + premiumPercent = 20 + }) { + const gasCosts = BigInt(gasPrice) * BigInt(gasLimit) + BigInt(l1Fee); + const relayerFee = BigInt(denomination) * BigInt(Math.floor(1e4 * relayerFeePercent)) / BigInt(1e4 * 100); + if (isEth) { + return (gasCosts + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } + const feeInEth = gasCosts + BigInt(ethRefund); + return (convertETHToTokenAmount(feeInEth, tokenPriceInWei, tokenDecimals) + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100) / BigInt(100); + } +} + + +/***/ }), + +/***/ 52049: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + GET_DEPOSITS: () => (/* reexport */ GET_DEPOSITS), + GET_ECHO_EVENTS: () => (/* reexport */ GET_ECHO_EVENTS), + GET_ENCRYPTED_NOTES: () => (/* reexport */ GET_ENCRYPTED_NOTES), + GET_GOVERNANCE_APY: () => (/* reexport */ GET_GOVERNANCE_APY), + GET_GOVERNANCE_EVENTS: () => (/* reexport */ GET_GOVERNANCE_EVENTS), + GET_NOTE_ACCOUNTS: () => (/* reexport */ GET_NOTE_ACCOUNTS), + GET_REGISTERED: () => (/* reexport */ GET_REGISTERED), + GET_STATISTIC: () => (/* reexport */ GET_STATISTIC), + GET_WITHDRAWALS: () => (/* reexport */ GET_WITHDRAWALS), + _META: () => (/* reexport */ _META), + getAllDeposits: () => (/* binding */ getAllDeposits), + getAllEncryptedNotes: () => (/* binding */ getAllEncryptedNotes), + getAllGovernanceEvents: () => (/* binding */ getAllGovernanceEvents), + getAllGraphEchoEvents: () => (/* binding */ getAllGraphEchoEvents), + getAllRegisters: () => (/* binding */ getAllRegisters), + getAllWithdrawals: () => (/* binding */ getAllWithdrawals), + getDeposits: () => (/* binding */ getDeposits), + getEncryptedNotes: () => (/* binding */ getEncryptedNotes), + getGovernanceEvents: () => (/* binding */ getGovernanceEvents), + getGraphEchoEvents: () => (/* binding */ getGraphEchoEvents), + getMeta: () => (/* binding */ getMeta), + getNoteAccounts: () => (/* binding */ getNoteAccounts), + getRegisters: () => (/* binding */ getRegisters), + getStatistic: () => (/* binding */ getStatistic), + getWithdrawals: () => (/* binding */ getWithdrawals), + queryGraph: () => (/* binding */ queryGraph) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/address.js +var address_address = __webpack_require__(30031); +// EXTERNAL MODULE: ./src/providers.ts + 40 modules +var providers = __webpack_require__(64819); +;// CONCATENATED MODULE: ./src/graphql/queries.ts + +const GET_STATISTIC = ` + query getStatistic($currency: String!, $amount: String!, $first: Int, $orderBy: BigInt, $orderDirection: String) { + deposits(first: $first, orderBy: $orderBy, orderDirection: $orderDirection, where: { currency: $currency, amount: $amount }) { + index + timestamp + blockNumber + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const _META = ` + query getMeta { + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_REGISTERED = ` + query getRegistered($first: Int, $fromBlock: Int) { + relayers(first: $first, orderBy: blockRegistration, orderDirection: asc, where: { + blockRegistration_gte: $fromBlock + }) { + id + address + ensName + blockRegistration + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_DEPOSITS = ` + query getDeposits($currency: String!, $amount: String!, $first: Int, $fromBlock: Int) { + deposits(first: $first, orderBy: index, orderDirection: asc, where: { + amount: $amount, + currency: $currency, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + commitment + index + timestamp + from + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_WITHDRAWALS = ` + query getWithdrawals($currency: String!, $amount: String!, $first: Int, $fromBlock: Int!) { + withdrawals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { + currency: $currency, + amount: $amount, + blockNumber_gte: $fromBlock + }) { + id + blockNumber + nullifier + to + fee + timestamp + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_NOTE_ACCOUNTS = ` + query getNoteAccount($address: String!) { + noteAccounts(where: { address: $address }) { + id + index + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ECHO_EVENTS = ` + query getNoteAccounts($first: Int, $fromBlock: Int) { + noteAccounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + id + blockNumber + address + encryptedAccount + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_ENCRYPTED_NOTES = ` + query getEncryptedNotes($first: Int, $fromBlock: Int) { + encryptedNotes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + index + transactionHash + encryptedNote + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_EVENTS = ` + query getGovernanceEvents($first: Int, $fromBlock: Int) { + proposals(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + proposer + target + startTime + endTime + description + } + votes(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + proposalId + voter + support + votes + from + input + } + delegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateTo + } + undelegates(first: $first, orderBy: blockNumber, orderDirection: asc, where: { blockNumber_gte: $fromBlock }) { + blockNumber + logIndex + transactionHash + account + delegateFrom + } + _meta { + block { + number + } + hasIndexingErrors + } + } +`; +const GET_GOVERNANCE_APY = ` + stakeDailyBurns(first: 30, orderBy: date, orderDirection: desc) { + id + date + dailyAmountBurned + } +`; + +;// CONCATENATED MODULE: ./src/graphql/index.ts +/* provided dependency */ var console = __webpack_require__(96763); + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + +const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; +const first = 1e3; +function queryGraph(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + query, + variables, + fetchDataOptions: fetchDataOptions2 + }) { + var _a; + const graphUrl = `${graphApi}/subgraphs/name/${subgraphName}`; + const { data, errors } = yield (0,providers/* fetchData */.Fd)(graphUrl, __spreadProps(__spreadValues({}, fetchDataOptions2), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + query, + variables + }) + })); + if (errors) { + throw new Error(JSON.stringify(errors)); + } + if ((_a = data == null ? void 0 : data._meta) == null ? void 0 : _a.hasIndexingErrors) { + throw new Error("Subgraph has indexing errors"); + } + return data; + }); +} +function getStatistic(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + deposits, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_STATISTIC, + variables: { + currency, + first: 10, + orderBy: "index", + orderDirection: "desc", + amount + }, + fetchDataOptions: fetchDataOptions2 + }); + const events = deposits.map((e) => ({ + timestamp: Number(e.timestamp), + leafIndex: Number(e.index), + blockNumber: Number(e.blockNumber) + })).reverse(); + const [lastEvent] = events.slice(-1); + return { + events, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getStatistic query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getMeta(_0) { + return __async(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { + try { + const { + _meta: { + block: { number: lastSyncBlock }, + hasIndexingErrors + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: _META, + fetchDataOptions: fetchDataOptions2 + }); + return { + lastSyncBlock, + hasIndexingErrors + }; + } catch (err) { + console.log("Error from getMeta query"); + console.log(err); + return { + lastSyncBlock: null, + hasIndexingErrors: null + }; + } + }); +} +function getRegisters({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_REGISTERED, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllRegisters(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + relayers: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Registers", + fromBlock: Number(firstEvent.blockRegistration), + toBlock: Number(lastEvent.blockRegistration), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockRegistration }) => blockRegistration !== lastEvent.blockRegistration); + fromBlock = Number(lastEvent.blockRegistration); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, address, ensName, blockRegistration }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockRegistration), + logIndex: Number(logIndex), + transactionHash, + ensName, + relayerAddress: (0,address_address/* getAddress */.b)(address) + }; + }); + return { + events: result, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllRegisters query"); + console.log(err); + return { events: [], lastSyncBlock: fromBlock }; + } + }); +} +function getDeposits({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_DEPOSITS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllDeposits(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + deposits: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Deposits", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, commitment, index, timestamp, from }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + commitment, + leafIndex: Number(index), + timestamp: Number(timestamp), + from: (0,address_address/* getAddress */.b)(from) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllDeposits query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getWithdrawals({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_WITHDRAWALS, + variables: { + currency, + amount, + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllWithdrawals(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + currency, + amount, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + withdrawals: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Withdrawals", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map(({ id, blockNumber, nullifier, to, fee, timestamp }) => { + const [transactionHash, logIndex] = id.split("-"); + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + nullifierHash: nullifier, + to: (0,address_address/* getAddress */.b)(to), + fee, + timestamp: Number(timestamp) + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllWithdrawals query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getNoteAccounts(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + address, + fetchDataOptions: fetchDataOptions2 + }) { + try { + const { + noteAccounts: events, + _meta: { + block: { number: lastSyncBlock } + } + } = yield queryGraph({ + graphApi, + subgraphName, + query: GET_NOTE_ACCOUNTS, + variables: { + address: address.toLowerCase() + }, + fetchDataOptions: fetchDataOptions2 + }); + return { + events, + lastSyncBlock + }; + } catch (err) { + console.log("Error from getNoteAccounts query"); + console.log(err); + return { + events: [], + lastSyncBlock: null + }; + } + }); +} +function getGraphEchoEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ECHO_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGraphEchoEvents(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + noteAccounts: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EchoEvents", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => { + const [transactionHash, logIndex] = e.id.split("-"); + return { + blockNumber: Number(e.blockNumber), + logIndex: Number(logIndex), + transactionHash, + address: (0,address_address/* getAddress */.b)(e.address), + encryptedAccount: e.encryptedAccount + }; + }); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGraphEchoEvents query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getEncryptedNotes({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_ENCRYPTED_NOTES, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllEncryptedNotes(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const events = []; + let lastSyncBlock = fromBlock; + while (true) { + let { + encryptedNotes: result2, + _meta: { + // eslint-disable-next-line prefer-const + block: { number: currentBlock } + } + } = yield getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + if (isEmptyArray(result2)) { + break; + } + const [firstEvent] = result2; + const [lastEvent2] = result2.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "EncryptedNotes", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: result2.length + }); + } + if (result2.length < 900) { + events.push(...result2); + break; + } + result2 = result2.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + events.push(...result2); + } + if (!events.length) { + return { + events: [], + lastSyncBlock + }; + } + const result = events.map((e) => ({ + blockNumber: Number(e.blockNumber), + logIndex: Number(e.index), + transactionHash: e.transactionHash, + encryptedNote: e.encryptedNote + })); + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllEncryptedNotes query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} +function getGovernanceEvents({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2 +}) { + return queryGraph({ + graphApi, + subgraphName, + query: GET_GOVERNANCE_EVENTS, + variables: { + first, + fromBlock + }, + fetchDataOptions: fetchDataOptions2 + }); +} +function getAllGovernanceEvents(_0) { + return __async(this, arguments, function* ({ + graphApi, + subgraphName, + fromBlock, + fetchDataOptions: fetchDataOptions2, + onProgress + }) { + try { + const result = []; + let lastSyncBlock = fromBlock; + while (true) { + const { + proposals, + votes, + delegates, + undelegates, + _meta: { + block: { number: currentBlock } + } + } = yield getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 }); + lastSyncBlock = currentBlock; + const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length; + if (eventsLength === 0) { + break; + } + const formattedProposals = proposals.map( + ({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "ProposalCreated", + id: Number(proposalId), + proposer: (0,address_address/* getAddress */.b)(proposer), + target: (0,address_address/* getAddress */.b)(target), + startTime: Number(startTime), + endTime: Number(endTime), + description + }; + } + ); + const formattedVotes = votes.map( + ({ blockNumber, logIndex, transactionHash, proposalId, voter, support, votes: votes2, from, input }) => { + if (!input || input.length > 2048) { + input = ""; + } + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Voted", + proposalId: Number(proposalId), + voter: (0,address_address/* getAddress */.b)(voter), + support, + votes: votes2, + from: (0,address_address/* getAddress */.b)(from), + input + }; + } + ); + const formattedDelegates = delegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateTo }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Delegated", + account: (0,address_address/* getAddress */.b)(account), + delegateTo: (0,address_address/* getAddress */.b)(delegateTo) + }; + } + ); + const formattedUndelegates = undelegates.map( + ({ blockNumber, logIndex, transactionHash, account, delegateFrom }) => { + return { + blockNumber: Number(blockNumber), + logIndex: Number(logIndex), + transactionHash, + event: "Undelegated", + account: (0,address_address/* getAddress */.b)(account), + delegateFrom: (0,address_address/* getAddress */.b)(delegateFrom) + }; + } + ); + let formattedEvents = [ + ...formattedProposals, + ...formattedVotes, + ...formattedDelegates, + ...formattedUndelegates + ].sort((a, b) => { + if (a.blockNumber === b.blockNumber) { + return a.logIndex - b.logIndex; + } + return a.blockNumber - b.blockNumber; + }); + if (eventsLength < 900) { + result.push(...formattedEvents); + break; + } + const [firstEvent] = formattedEvents; + const [lastEvent2] = formattedEvents.slice(-1); + if (typeof onProgress === "function") { + onProgress({ + type: "Governance Events", + fromBlock: Number(firstEvent.blockNumber), + toBlock: Number(lastEvent2.blockNumber), + count: eventsLength + }); + } + formattedEvents = formattedEvents.filter(({ blockNumber }) => blockNumber !== lastEvent2.blockNumber); + fromBlock = Number(lastEvent2.blockNumber); + result.push(...formattedEvents); + } + const [lastEvent] = result.slice(-1); + return { + events: result, + lastSyncBlock: lastEvent && lastEvent.blockNumber >= lastSyncBlock ? lastEvent.blockNumber + 1 : lastSyncBlock + }; + } catch (err) { + console.log("Error from getAllGovernance query"); + console.log(err); + return { + events: [], + lastSyncBlock: fromBlock + }; + } + }); +} + + +/***/ }), + +/***/ 5217: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ s: () => (/* binding */ MerkleTreeService) +/* harmony export */ }); +/* harmony import */ var worker_threads__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47882); +/* harmony import */ var worker_threads__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(worker_threads__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(41217); +/* harmony import */ var _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67418); +/* harmony import */ var _mimc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(22901); +/* provided dependency */ var console = __webpack_require__(96763); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + +class MerkleTreeService { + constructor({ + netId, + amount, + currency, + Tornado, + commitmentHex, + merkleTreeHeight = 20, + emptyElement = "21663839004416932945382355908790599225266501822907911457504978515578255421292", + merkleWorkerPath + }) { + const instanceName = `${netId}_${currency}_${amount}`; + this.currency = currency; + this.amount = amount; + this.netId = Number(netId); + this.Tornado = Tornado; + this.instanceName = instanceName; + this.commitmentHex = commitmentHex; + this.merkleTreeHeight = merkleTreeHeight; + this.emptyElement = emptyElement; + this.merkleWorkerPath = merkleWorkerPath; + } + createTree(events) { + return __async(this, null, function* () { + const { hash: hashFunction } = yield _mimc__WEBPACK_IMPORTED_MODULE_3__/* .mimc */ .f.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (_utils__WEBPACK_IMPORTED_MODULE_2__/* .isNode */ .Ll) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new worker_threads__WEBPACK_IMPORTED_MODULE_0__.Worker(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + elements: events, + zeroElement: this.emptyElement + }); + }); + return _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.MerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.MerkleTree(this.merkleTreeHeight, events, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + createPartialTree(_0) { + return __async(this, arguments, function* ({ edge, elements }) { + const { hash: hashFunction } = yield _mimc__WEBPACK_IMPORTED_MODULE_3__/* .mimc */ .f.getHash(); + if (this.merkleWorkerPath) { + console.log("Using merkleWorker\n"); + try { + if (_utils__WEBPACK_IMPORTED_MODULE_2__/* .isNode */ .Ll) { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new worker_threads__WEBPACK_IMPORTED_MODULE_0__.Worker(this.merkleWorkerPath, { + workerData: { + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + } + }); + worker.on("message", resolve); + worker.on("error", reject); + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }); + return _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } else { + const merkleWorkerPromise = new Promise((resolve, reject) => { + const worker = new Worker(this.merkleWorkerPath); + worker.onmessage = (e) => { + resolve(e.data); + }; + worker.onerror = (e) => { + reject(e); + }; + worker.postMessage({ + merkleTreeHeight: this.merkleTreeHeight, + edge, + elements, + zeroElement: this.emptyElement + }); + }); + return _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.PartialMerkleTree.deserialize(JSON.parse(yield merkleWorkerPromise), hashFunction); + } + } catch (err) { + console.log("merkleWorker failed, falling back to synchronous merkle tree"); + console.log(err); + } + } + return new _tornado_fixed_merkle_tree__WEBPACK_IMPORTED_MODULE_1__.PartialMerkleTree(this.merkleTreeHeight, edge, elements, { + zeroElement: this.emptyElement, + hashFunction + }); + }); + } + verifyTree(events) { + return __async(this, null, function* () { + console.log( + ` +Creating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while +` + ); + console.time("Created tree in"); + const tree = yield this.createTree(events.map(({ commitment }) => commitment)); + console.timeEnd("Created tree in"); + console.log(""); + const isKnownRoot = yield this.Tornado.isKnownRoot((0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(BigInt(tree.root))); + if (!isKnownRoot) { + const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`; + throw new Error(errMsg); + } + return tree; + }); + } +} + + +/***/ }), + +/***/ 22901: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ f: () => (/* binding */ mimc), +/* harmony export */ p: () => (/* binding */ Mimc) +/* harmony export */ }); +/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89082); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +class Mimc { + constructor() { + this.mimcPromise = this.initMimc(); + } + initMimc() { + return __async(this, null, function* () { + this.sponge = yield (0,circomlibjs__WEBPACK_IMPORTED_MODULE_0__/* .buildMimcSponge */ .HI)(); + this.hash = (left, right) => { + var _a, _b; + return (_b = this.sponge) == null ? void 0 : _b.F.toString((_a = this.sponge) == null ? void 0 : _a.multiHash([BigInt(left), BigInt(right)])); + }; + }); + } + getHash() { + return __async(this, null, function* () { + yield this.mimcPromise; + return { + sponge: this.sponge, + hash: this.hash + }; + }); + } +} +const mimc = new Mimc(); + + +/***/ }), + +/***/ 48486: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ C: () => (/* binding */ multicall) +/* harmony export */ }); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function multicall(Multicall2, calls) { + return __async(this, null, function* () { + const calldata = calls.map((call) => { + var _a, _b, _c; + const target = ((_a = call.contract) == null ? void 0 : _a.target) || call.address; + const callInterface = ((_b = call.contract) == null ? void 0 : _b.interface) || call.interface; + return { + target, + callData: callInterface.encodeFunctionData(call.name, call.params), + allowFailure: (_c = call.allowFailure) != null ? _c : false + }; + }); + const returnData = yield Multicall2.aggregate3.staticCall(calldata); + const res = returnData.map((call, i) => { + var _a; + const callInterface = ((_a = calls[i].contract) == null ? void 0 : _a.interface) || calls[i].interface; + const [result, data] = call; + const decodeResult = result && data && data !== "0x" ? callInterface.decodeFunctionResult(calls[i].name, data) : null; + return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult; + }); + return res; + }); +} + + +/***/ }), + +/***/ 59499: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AE: () => (/* binding */ addNetwork), +/* harmony export */ Af: () => (/* binding */ enabledChains), +/* harmony export */ RY: () => (/* binding */ getNetworkConfig), +/* harmony export */ Zh: () => (/* binding */ getInstanceByAddress), +/* harmony export */ cF: () => (/* binding */ getSubdomains), +/* harmony export */ cX: () => (/* binding */ customConfig), +/* harmony export */ sb: () => (/* binding */ defaultConfig), +/* harmony export */ zj: () => (/* binding */ getConfig), +/* harmony export */ zr: () => (/* binding */ NetId) +/* harmony export */ }); + +var __defProp = Object.defineProperty; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var NetId = /* @__PURE__ */ ((NetId2) => { + NetId2[NetId2["MAINNET"] = 1] = "MAINNET"; + NetId2[NetId2["BSC"] = 56] = "BSC"; + NetId2[NetId2["POLYGON"] = 137] = "POLYGON"; + NetId2[NetId2["OPTIMISM"] = 10] = "OPTIMISM"; + NetId2[NetId2["ARBITRUM"] = 42161] = "ARBITRUM"; + NetId2[NetId2["GNOSIS"] = 100] = "GNOSIS"; + NetId2[NetId2["AVALANCHE"] = 43114] = "AVALANCHE"; + NetId2[NetId2["SEPOLIA"] = 11155111] = "SEPOLIA"; + return NetId2; +})(NetId || {}); +const theGraph = { + name: "Hosted Graph", + url: "https://api.thegraph.com" +}; +const tornado = { + name: "Tornado Subgraphs", + url: "https://tornadocash-rpc.com" +}; +const defaultConfig = { + [1 /* MAINNET */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 80, + fast: 50, + standard: 25, + low: 8 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Mainnet", + deployedBlock: 9116966, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + mevblockerRPC: { + name: "MevblockerRPC", + url: "https://rpc.mevblocker.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/ethereum-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://eth-mainnet.nodereal.io/v1/1659dfb40aa24bbb8153a677b98064d7" + }, + notadegenRPC: { + name: "NotADegen RPC", + url: "https://rpc.notadegen.com/eth" + }, + keydonixRPC: { + name: "Keydonix RPC", + url: "https://ethereum.keydonix.com/v1/mainnet" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/eth" + } + }, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b", + echoContract: "0x9B27DD5Bb15d42DC224FCD0B7caEbBe16161Df42", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornContract: "0x77777FeDdddFfC19Ff86DB637967013e6C6A116C", + governanceContract: "0x5efda50f22d34F262c29268506C5Fa42cB56A1Ce", + stakingRewardsContract: "0x5B3f656C80E8ddb9ec01Dd9018815576E9238c29", + registryContract: "0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2", + aggregatorContract: "0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49", + reverseRecordsContract: "0x3671aE578E63FdF66ad4F3E12CC0c0d71Ac7510C", + tornadoSubgraph: "tornadocash/mainnet-tornado-subgraph", + registrySubgraph: "tornadocash/tornado-relayer-registry", + governanceSubgraph: "tornadocash/tornado-governance", + subgraphs: { + tornado, + theGraph + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc", + "1": "0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936", + "10": "0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF", + "100": "0xA160cdAB225685dA1d56aa342Ad8841c3b53f291" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3", + "1000": "0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144", + "10000": "0x07687e702b410Fa43f4cB4Af7FA097918ffD2730", + "100000": "0x23773E65ed146A459791799d01336DB287f25334" + }, + tokenAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + }, + cdai: { + instanceAddress: { + "5000": "0x22aaA7720ddd5388A3c0A3333430953C68f1849b", + "50000": "0x03893a7c7463AE47D46bc7f091665f1893656003", + "500000": "0x2717c5e28cf931547B621a5dddb772Ab6A35B701", + "5000000": "0xD21be7248e0197Ee08E0c20D4a96DEBdaC3D20Af" + }, + tokenAddress: "0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643", + tokenGasLimit: 2e5, + symbol: "cDAI", + decimals: 8, + gasLimit: 7e5 + }, + usdc: { + instanceAddress: { + "100": "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307", + "1000": "0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D" + }, + tokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + tokenGasLimit: 7e4, + symbol: "USDC", + decimals: 6, + gasLimit: 7e5 + }, + usdt: { + instanceAddress: { + "100": "0x169AD27A470D064DEDE56a2D3ff727986b15D52B", + "1000": "0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f" + }, + tokenAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + tokenGasLimit: 7e4, + symbol: "USDT", + decimals: 6, + gasLimit: 7e5 + }, + wbtc: { + instanceAddress: { + "0.1": "0x178169B423a011fff22B9e3F3abeA13414dDD0F1", + "1": "0x610B717796ad172B316836AC95a2ffad065CeaB4", + "10": "0xbB93e510BbCD0B7beb5A853875f9eC60275CF498" + }, + tokenAddress: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", + tokenGasLimit: 7e4, + symbol: "WBTC", + decimals: 8, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "mainnet-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 11474695, + NOTE_ACCOUNT_BLOCK: 11842486, + ENCRYPTED_NOTES_BLOCK: 12143762, + REGISTRY_BLOCK: 14173129, + MINING_BLOCK_TIME: 15 + } + }, + [56 /* BSC */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 5, + fast: 5, + standard: 5, + low: 5 + }, + nativeCurrency: "bnb", + currencyName: "BNB", + explorerUrl: "https://bscscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Binance Smart Chain", + deployedBlock: 8158799, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/bsc-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/bsc" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://bsc-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/bsc-mainnet" + }, + noderealRPC: { + name: "NodeReal RPC", + url: "https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3" + }, + oneRPC: { + name: "1RPC", + url: "https://1rpc.io/bnb" + } + }, + tokens: { + bnb: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "BNB", + decimals: 18 + } + }, + ensSubdomainKey: "bsc-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 8159269, + ENCRYPTED_NOTES_BLOCK: 8159269 + } + }, + [137 /* POLYGON */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 100, + fast: 75, + standard: 50, + low: 30 + }, + nativeCurrency: "matic", + currencyName: "MATIC", + explorerUrl: "https://polygonscan.com", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Polygon (Matic) Network", + deployedBlock: 16257962, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + gasPriceOracleContract: "0xF81A8D8D3581985D3969fe53bFA67074aDFa8F3C", + tornadoSubgraph: "tornadocash/matic-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + chainnodes: { + name: "Tornado RPC", + url: "https://polygon-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/polygon-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/matic" + } + }, + tokens: { + matic: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "MATIC", + decimals: 18 + } + }, + ensSubdomainKey: "polygon-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 16257996, + ENCRYPTED_NOTES_BLOCK: 16257996 + } + }, + [10 /* OPTIMISM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 1e-3, + fast: 1e-3, + standard: 1e-3, + low: 1e-3 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://optimistic.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Optimism", + deployedBlock: 2243689, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + ovmGasPriceOracleContract: "0x420000000000000000000000000000000000000F", + tornadoSubgraph: "tornadocash/optimism-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/op" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://optimism-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + optimism: { + name: "Optimism RPC", + url: "https://mainnet.optimism.io" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/optimism-mainnet" + }, + oneRpc: { + name: "1RPC", + url: "https://1rpc.io/op" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "optimism-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 2243694, + ENCRYPTED_NOTES_BLOCK: 2243694 + } + }, + [42161 /* ARBITRUM */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 4, + fast: 3, + standard: 2.52, + low: 2.29 + }, + nativeCurrency: "eth", + currencyName: "ETH", + explorerUrl: "https://arbiscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Arbitrum One", + deployedBlock: 3430648, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/arbitrum-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/arbitrum" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://arbitrum-one.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + arbitrum: { + name: "Arbitrum RPC", + url: "https://arb1.arbitrum.io/rpc" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + oneRpc: { + name: "1rpc", + url: "https://1rpc.io/arb" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x84443CFd09A48AF6eF360C6976C5392aC5023a1F", + "1": "0xd47438C816c9E7f2E2888E060936a499Af9582b3", + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD" + }, + symbol: "ETH", + decimals: 18 + } + }, + ensSubdomainKey: "arbitrum-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 3430605, + ENCRYPTED_NOTES_BLOCK: 3430605 + } + }, + [100 /* GNOSIS */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 6, + fast: 5, + standard: 4, + low: 1 + }, + nativeCurrency: "xdai", + currencyName: "xDAI", + explorerUrl: "https://gnosisscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Gnosis Chain", + deployedBlock: 17754561, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/xdai-tornado-subgraph", + subgraphs: { + tornado, + theGraph + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/gnosis" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://gnosis-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + }, + gnosis: { + name: "Gnosis RPC", + url: "https://rpc.gnosischain.com" + }, + stackup: { + name: "Stackup RPC", + url: "https://public.stackup.sh/api/v1/node/arbitrum-one" + }, + blockPi: { + name: "BlockPi", + url: "https://gnosis.blockpi.network/v1/rpc/public" + } + }, + tokens: { + xdai: { + instanceAddress: { + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "1000": "0xdf231d99Ff8b6c6CBF4E9B9a945CBAcEF9339178", + "10000": "0xaf4c0B70B2Ea9FB7487C7CbB37aDa259579fe040", + "100000": "0xa5C2254e4253490C54cef0a4347fddb8f75A4998" + }, + symbol: "xDAI", + decimals: 18 + } + }, + ensSubdomainKey: "gnosis-tornado", + pollInterval: 15, + constants: { + NOTE_ACCOUNT_BLOCK: 17754564, + ENCRYPTED_NOTES_BLOCK: 17754564 + } + }, + [43114 /* AVALANCHE */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 225, + fast: 35, + standard: 25, + low: 25 + }, + nativeCurrency: "avax", + currencyName: "AVAX", + explorerUrl: "https://snowtrace.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Avalanche Mainnet", + deployedBlock: 4429818, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x0D5550d52428E7e3175bfc9550207e4ad3859b17", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + offchainOracleContract: "0x0AdDd25a91563696D8567Df78D5A01C9a991F9B8", + tornadoSubgraph: "tornadocash/avalanche-tornado-subgraph", + subgraphs: { + theGraph + }, + rpcUrls: { + oneRPC: { + name: "OneRPC", + url: "https://1rpc.io/avax/c" + }, + avalancheRPC: { + name: "Avalanche RPC", + url: "https://api.avax.network/ext/bc/C/rpc" + }, + meowRPC: { + name: "Meow RPC", + url: "https://avax.meowrpc.com" + } + }, + tokens: { + avax: { + instanceAddress: { + "10": "0x330bdFADE01eE9bF63C209Ee33102DD334618e0a", + "100": "0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD", + "500": "0xaf8d1839c3c67cf571aa74B5c12398d4901147B3" + }, + symbol: "AVAX", + decimals: 18 + } + }, + ensSubdomainKey: "avalanche-tornado", + pollInterval: 10, + constants: { + NOTE_ACCOUNT_BLOCK: 4429813, + ENCRYPTED_NOTES_BLOCK: 4429813 + } + }, + [11155111 /* SEPOLIA */]: { + rpcCallRetryAttempt: 15, + gasPrices: { + instant: 2, + fast: 2, + standard: 2, + low: 2 + }, + nativeCurrency: "eth", + currencyName: "SepoliaETH", + explorerUrl: "https://sepolia.etherscan.io", + merkleTreeHeight: 20, + emptyElement: "21663839004416932945382355908790599225266501822907911457504978515578255421292", + networkName: "Ethereum Sepolia", + deployedBlock: 5594395, + multicallContract: "0xcA11bde05977b3631167028862bE2a173976CA11", + routerContract: "0x1572AFE6949fdF51Cb3E0856216670ae9Ee160Ee", + echoContract: "0xa75BF2815618872f155b7C4B0C81bF990f5245E4", + tornContract: "0x3AE6667167C0f44394106E197904519D808323cA", + governanceContract: "0xe5324cD7602eeb387418e594B87aCADee08aeCAD", + stakingRewardsContract: "0x6d0018890751Efd31feb8166711B16732E2b496b", + registryContract: "0x1428e5d2356b13778A13108b10c440C83011dfB8", + aggregatorContract: "0x4088712AC9fad39ea133cdb9130E465d235e9642", + reverseRecordsContract: "0xEc29700C0283e5Be64AcdFe8077d6cC95dE23C23", + tornadoSubgraph: "tornadocash/sepolia-tornado-subgraph", + subgraphs: { + tornado + }, + rpcUrls: { + tornado: { + name: "Tornado RPC", + url: "https://tornadocash-rpc.com/sepolia" + }, + sepolia: { + name: "Sepolia RPC", + url: "https://rpc.sepolia.org" + }, + chainnodes: { + name: "Chainnodes RPC", + url: "https://sepolia.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607" + } + }, + tokens: { + eth: { + instanceAddress: { + "0.1": "0x8C4A04d872a6C1BE37964A21ba3a138525dFF50b", + "1": "0x8cc930096B4Df705A007c4A039BDFA1320Ed2508", + "10": "0x8D10d506D29Fc62ABb8A290B99F66dB27Fc43585", + "100": "0x44c5C92ed73dB43888210264f0C8b36Fd68D8379" + }, + symbol: "ETH", + decimals: 18 + }, + dai: { + instanceAddress: { + "100": "0x6921fd1a97441dd603a997ED6DDF388658daf754", + "1000": "0x50a637770F5d161999420F7d70d888DE47207145", + "10000": "0xecD649870407cD43923A816Cc6334a5bdf113621", + "100000": "0x73B4BD04bF83206B6e979BE2507098F92EDf4F90" + }, + tokenAddress: "0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357", + tokenGasLimit: 7e4, + symbol: "DAI", + decimals: 18, + gasLimit: 7e5 + } + }, + ensSubdomainKey: "sepolia-tornado", + pollInterval: 15, + constants: { + GOVERNANCE_BLOCK: 5594395, + NOTE_ACCOUNT_BLOCK: 5594395, + ENCRYPTED_NOTES_BLOCK: 5594395, + MINING_BLOCK_TIME: 15 + } + } +}; +const enabledChains = Object.values(NetId).filter((n) => typeof n === "number"); +let customConfig = {}; +function addNetwork(newConfig) { + enabledChains.push( + ...Object.keys(newConfig).map((netId) => Number(netId)).filter((netId) => !enabledChains.includes(netId)) + ); + customConfig = __spreadValues(__spreadValues({}, customConfig), newConfig); +} +function getNetworkConfig() { + const allConfig = __spreadValues(__spreadValues({}, defaultConfig), customConfig); + return enabledChains.reduce((acc, curr) => { + acc[curr] = allConfig[curr]; + return acc; + }, {}); +} +function getConfig(netId) { + const allConfig = getNetworkConfig(); + const chainConfig = allConfig[netId]; + if (!chainConfig) { + const errMsg = `No config found for network ${netId}!`; + throw new Error(errMsg); + } + return chainConfig; +} +function getInstanceByAddress({ netId, address }) { + const { tokens } = getConfig(netId); + for (const [currency, { instanceAddress }] of Object.entries(tokens)) { + for (const [amount, instance] of Object.entries(instanceAddress)) { + if (instance === address) { + return { + amount, + currency + }; + } + } + } +} +function getSubdomains() { + const allConfig = getNetworkConfig(); + return enabledChains.map((chain) => allConfig[chain].ensSubdomainKey); +} + + +/***/ }), + +/***/ 30200: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $J: () => (/* binding */ parseNumber), +/* harmony export */ Dl: () => (/* binding */ parseUrl), +/* harmony export */ Do: () => (/* binding */ parseKey), +/* harmony export */ _p: () => (/* binding */ parseRecoveryKey), +/* harmony export */ or: () => (/* binding */ parseAddress), +/* harmony export */ qc: () => (/* binding */ parseMnemonic), +/* harmony export */ yJ: () => (/* binding */ parseRelayer) +/* harmony export */ }); +/* harmony import */ var commander__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(60684); +/* harmony import */ var commander__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(commander__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30031); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37514); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20415); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67418); + + + + +function parseNumber(value) { + if (!value || isNaN(Number(value))) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Number"); + } + return Number(value); +} +function parseUrl(value) { + if (!value || !(0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .validateUrl */ .wv)(value, ["http:", "https:"])) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid URL"); + } + return value; +} +function parseRelayer(value) { + if (!value || !(value.endsWith(".eth") || (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .validateUrl */ .wv)(value, ["http:", "https:"]))) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Relayer ETH address or URL"); + } + return value; +} +function parseAddress(value) { + if (!value) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Address"); + } + try { + return (0,ethers__WEBPACK_IMPORTED_MODULE_2__/* .getAddress */ .b)(value); + } catch (e) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Address"); + } +} +function parseMnemonic(value) { + if (!value) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Mnemonic"); + } + try { + ethers__WEBPACK_IMPORTED_MODULE_3__/* .Mnemonic */ .v.fromPhrase(value); + } catch (e) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Mnemonic"); + } + return value; +} +function parseKey(value) { + if (!value) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Private Key"); + } + if (value.length === 64) { + value = "0x" + value; + } + try { + (0,ethers__WEBPACK_IMPORTED_MODULE_4__/* .computeAddress */ .K)(value); + } catch (e) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Private Key"); + } + return value; +} +function parseRecoveryKey(value) { + if (!value) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Recovery Key"); + } + try { + (0,ethers__WEBPACK_IMPORTED_MODULE_4__/* .computeAddress */ .K)("0x" + value); + } catch (e) { + throw new commander__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentError("Invalid Recovery Key"); + } + return value; +} + + +/***/ }), + +/***/ 85111: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Hr: () => (/* binding */ Pedersen), +/* harmony export */ NO: () => (/* binding */ pedersen), +/* harmony export */ UB: () => (/* binding */ buffPedersenHash) +/* harmony export */ }); +/* harmony import */ var circomlibjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89082); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +class Pedersen { + constructor() { + this.pedersenPromise = this.initPedersen(); + } + initPedersen() { + return __async(this, null, function* () { + this.pedersenHash = yield (0,circomlibjs__WEBPACK_IMPORTED_MODULE_0__/* .buildPedersenHash */ .vu)(); + this.babyJub = this.pedersenHash.babyJub; + }); + } + unpackPoint(buffer) { + return __async(this, null, function* () { + var _a, _b; + yield this.pedersenPromise; + return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); + }); + } + toStringBuffer(buffer) { + var _a; + return (_a = this.babyJub) == null ? void 0 : _a.F.toString(buffer); + } +} +const pedersen = new Pedersen(); +function buffPedersenHash(buffer) { + return __async(this, null, function* () { + const [hash] = yield pedersen.unpackPoint(buffer); + return pedersen.toStringBuffer(hash); + }); +} + + +/***/ }), + +/***/ 34525: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ TokenPriceOracle) +/* harmony export */ }); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99770); +/* harmony import */ var _multicall__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48486); + + + +class TokenPriceOracle { + constructor(provider, multicall2, oracle) { + this.provider = provider; + this.multicall = multicall2; + this.oracle = oracle; + } + fetchPrices(tokens) { + if (!this.oracle) { + return new Promise((resolve) => resolve(tokens.map(() => (0,ethers__WEBPACK_IMPORTED_MODULE_0__/* .parseEther */ .g5)("0.0001")))); + } + return (0,_multicall__WEBPACK_IMPORTED_MODULE_1__/* .multicall */ .C)( + this.multicall, + tokens.map((token) => ({ + contract: this.oracle, + name: "getRateToEth", + params: [token, true] + })) + ); + } +} + + +/***/ }), + +/***/ 64819: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + D2: () => (/* binding */ TornadoBrowserProvider), + Vr: () => (/* binding */ TornadoRpcSigner), + Gd: () => (/* binding */ TornadoVoidSigner), + nA: () => (/* binding */ TornadoWallet), + mJ: () => (/* binding */ defaultUserAgent), + hd: () => (/* binding */ providers_fetch), + Fd: () => (/* binding */ fetchData), + uY: () => (/* binding */ fetchGetUrlFunc), + bD: () => (/* binding */ getGasOraclePlugin), + WU: () => (/* binding */ getHttpAgent), + sO: () => (/* binding */ getProvider), + MF: () => (/* binding */ getProviderWithNetId), + zr: () => (/* binding */ populateTransaction) +}); + +// EXTERNAL MODULE: ./node_modules/cross-fetch/dist/browser-ponyfill.js +var browser_ponyfill = __webpack_require__(74945); +var browser_ponyfill_default = /*#__PURE__*/__webpack_require__.n(browser_ponyfill); +// EXTERNAL MODULE: http-proxy-agent (ignored) +var http_proxy_agent_ignored_ = __webpack_require__(60513); +// EXTERNAL MODULE: https-proxy-agent (ignored) +var https_proxy_agent_ignored_ = __webpack_require__(2378); +// EXTERNAL MODULE: socks-proxy-agent (ignored) +var socks_proxy_agent_ignored_ = __webpack_require__(60290); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/plugins-network.js + + +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +/** + * A **NetworkPlugin** provides additional functionality on a [[Network]]. + */ +class NetworkPlugin { + /** + * The name of the plugin. + * + * It is recommended to use reverse-domain-notation, which permits + * unique names with a known authority as well as hierarchal entries. + */ + name; + /** + * Creates a new **NetworkPlugin**. + */ + constructor(name) { + (0,properties/* defineProperties */.n)(this, { name }); + } + /** + * Creates a copy of this plugin. + */ + clone() { + return new NetworkPlugin(this.name); + } +} +/** + * A **GasCostPlugin** allows a network to provide alternative values when + * computing the intrinsic gas required for a transaction. + */ +class GasCostPlugin extends NetworkPlugin { + /** + * The block number to treat these values as valid from. + * + * This allows a hardfork to have updated values included as well as + * mulutiple hardforks to be supported. + */ + effectiveBlock; + /** + * The transactions base fee. + */ + txBase; + /** + * The fee for creating a new account. + */ + txCreate; + /** + * The fee per zero-byte in the data. + */ + txDataZero; + /** + * The fee per non-zero-byte in the data. + */ + txDataNonzero; + /** + * The fee per storage key in the [[link-eip-2930]] access list. + */ + txAccessListStorageKey; + /** + * The fee per address in the [[link-eip-2930]] access list. + */ + txAccessListAddress; + /** + * Creates a new GasCostPlugin from %%effectiveBlock%% until the + * latest block or another GasCostPlugin supercedes that block number, + * with the associated %%costs%%. + */ + constructor(effectiveBlock, costs) { + if (effectiveBlock == null) { + effectiveBlock = 0; + } + super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`); + const props = { effectiveBlock }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; + } + (0,errors/* assertArgument */.MR)(typeof (value) === "number", `invalud value for ${name}`, "costs", costs); + props[name] = value; + } + set("txBase", 21000); + set("txCreate", 32000); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + (0,properties/* defineProperties */.n)(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +/** + * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry + * Contract address and the target network to use when using that + * contract. + * + * Various testnets have their own instance of the contract to use, but + * in general, the mainnet instance supports multi-chain addresses and + * should be used. + */ +class EnsPlugin extends NetworkPlugin { + /** + * The ENS Registrty Contract address. + */ + address; + /** + * The chain ID that the ENS contract lives on. + */ + targetNetwork; + /** + * Creates a new **EnsPlugin** connected to %%address%% on the + * %%targetNetwork%%. The default ENS address and mainnet is used + * if unspecified. + */ + constructor(address, targetNetwork) { + super("org.ethers.plugins.network.Ens"); + (0,properties/* defineProperties */.n)(this, { + address: (address || EnsAddress), + targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } +} +/** + * A **FeeDataNetworkPlugin** allows a network to provide and alternate + * means to specify its fee data. + * + * For example, a network which does not support [[link-eip-1559]] may + * choose to use a Gas Station site to approximate the gas price. + */ +class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + /** + * The fee data function provided to the constructor. + */ + get feeDataFunc() { + return this.#feeDataFunc; + } + /** + * Creates a new **FeeDataNetworkPlugin**. + */ + constructor(feeDataFunc) { + super("org.ethers.plugins.network.FeeData"); + this.#feeDataFunc = feeDataFunc; + } + /** + * Resolves to the fee data. + */ + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} +class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { + #url; + #processFunc; + /** + * The URL to initialize the FetchRequest with in %%processFunc%%. + */ + get url() { return this.#url; } + /** + * The callback to use when computing the FeeData. + */ + get processFunc() { return this.#processFunc; } + /** + * Creates a new **FetchUrlFeeDataNetworkPlugin** which will + * be used when computing the fee data for the network. + */ + constructor(url, processFunc) { + super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + this.#url = url; + this.#processFunc = processFunc; + } + // We are immutable, so we can serve as our own clone + clone() { return this; } +} +/* +export class CustomBlockNetworkPlugin extends NetworkPlugin { + readonly #blockFunc: (provider: Provider, block: BlockParams) => Block; + readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block; + + constructor(blockFunc: (provider: Provider, block: BlockParams) => Block, blockWithTxsFunc: (provider: Provider, block: BlockParams) => Block) { + super("org.ethers.network-plugins.custom-block"); + this.#blockFunc = blockFunc; + this.#blockWithTxsFunc = blockWithTxsFunc; + } + + async getBlock(provider: Provider, block: BlockParams): Promise> { + return await this.#blockFunc(provider, block); + } + + async getBlockions(provider: Provider, block: BlockParams): Promise> { + return await this.#blockWithTxsFunc(provider, block); + } + + clone(): CustomBlockNetworkPlugin { + return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc); + } +} +*/ +//# sourceMappingURL=plugins-network.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var utils_data = __webpack_require__(36212); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/base64-browser.js +// utils/base64-browser + +function decodeBase64(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for (let i = 0; i < textData.length; i++) { + data[i] = textData.charCodeAt(i); + } + return (0,utils_data/* getBytes */.q5)(data); +} +function encodeBase64(_data) { + const data = (0,utils_data/* getBytes */.q5)(_data); + let textData = ""; + for (let i = 0; i < data.length; i++) { + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} +//# sourceMappingURL=base64-browser.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/utf8.js +var utf8 = __webpack_require__(87303); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/geturl-browser.js + +// @TODO: timeout is completely ignored; start a Promise.any with a reject? +function createGetUrl(options) { + async function getUrl(req, _signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + (0,errors/* assert */.vA)(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + (0,errors/* assert */.vA)(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + let signal = undefined; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { controller.abort(); }); + } + const init = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || undefined, + signal + }; + const resp = await fetch(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = (respBody == null) ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, body + }; + } + return getUrl; +} +// @TODO: remove in v7; provided for backwards compat +const defaultGetUrl = createGetUrl({}); +async function getUrl(req, _signal) { + return defaultGetUrl(req, _signal); +} +//# sourceMappingURL=geturl-browser.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/fetch.js +/** + * Fetching content from the web is environment-specific, so Ethers + * provides an abstraction that each environment can implement to provide + * this service. + * + * On [Node.js](link-node), the ``http`` and ``https`` libs are used to + * create a request object, register event listeners and process data + * and populate the [[FetchResponse]]. + * + * In a browser, the [DOM fetch](link-js-fetch) is used, and the resulting + * ``Promise`` is waited on to retrieve the payload. + * + * The [[FetchRequest]] is responsible for handling many common situations, + * such as redirects, server throttling, authentication, etc. + * + * It also handles common gateways, such as IPFS and data URIs. + * + * @_section api/utils/fetching:Fetching Web Content [about-fetch] + */ + + + + + + +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +// The global FetchGetUrlFunc implementation. +let defaultGetUrlFunc = createGetUrl(); +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i"); +// If locked, new Gateways cannot be added +let locked = false; +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs +async function dataGatewayFunc(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": (match[1] || "text/plain"), + }, (match[2] ? decodeBase64(match[3]) : unpercent(match[3]))); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); + } +} +/** + * Returns a [[FetchGatewayFunc]] for fetching content from a standard + * IPFS gateway hosted at %%baseUrl%%. + */ +function getIpfsGatewayFunc(baseUrl) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); + } + return new FetchRequest(`${baseUrl}${match[2]}`); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); + } + } + return gatewayIpfs; +} +const Gateways = { + "data": dataGatewayFunc, + "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/") +}; +const fetchSignals = new WeakMap(); +/** + * @_ignore + */ +class FetchCancelSignal { + #listeners; + #cancelled; + constructor(request) { + this.#listeners = []; + this.#cancelled = false; + fetchSignals.set(request, () => { + if (this.#cancelled) { + return; + } + this.#cancelled = true; + for (const listener of this.#listeners) { + setTimeout(() => { listener(); }, 0); + } + this.#listeners = []; + }); + } + addListener(listener) { + (0,errors/* assert */.vA)(!this.#cancelled, "singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + this.#listeners.push(listener); + } + get cancelled() { return this.#cancelled; } + checkSignal() { + (0,errors/* assert */.vA)(!this.cancelled, "cancelled", "CANCELLED", {}); + } +} +// Check the signal, throwing if it is cancelled +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); + } + signal.checkSignal(); + return signal; +} +/** + * Represents a request for a resource using a URI. + * + * By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``, + * and ``IPFS:``. + * + * Additional schemes can be added globally using [[registerGateway]]. + * + * @example: + * req = new FetchRequest("https://www.ricmoo.com") + * resp = await req.send() + * resp.body.length + * //_result: + */ +class FetchRequest { + #allowInsecure; + #gzip; + #headers; + #method; + #timeout; + #url; + #body; + #bodyType; + #creds; + // Hooks + #preflight; + #process; + #retry; + #signal; + #throttle; + #getUrlFunc; + /** + * The fetch URL to request. + */ + get url() { return this.#url; } + set url(url) { + this.#url = String(url); + } + /** + * The fetch body, if any, to send as the request body. //(default: null)// + * + * When setting a body, the intrinsic ``Content-Type`` is automatically + * set and will be used if **not overridden** by setting a custom + * header. + * + * If %%body%% is null, the body is cleared (along with the + * intrinsic ``Content-Type``). + * + * If %%body%% is a string, the intrinsic ``Content-Type`` is set to + * ``text/plain``. + * + * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to + * ``application/octet-stream``. + * + * If %%body%% is any other object, the intrinsic ``Content-Type`` is + * set to ``application/json``. + */ + get body() { + if (this.#body == null) { + return null; + } + return new Uint8Array(this.#body); + } + set body(body) { + if (body == null) { + this.#body = undefined; + this.#bodyType = undefined; + } + else if (typeof (body) === "string") { + this.#body = (0,utf8/* toUtf8Bytes */.YW)(body); + this.#bodyType = "text/plain"; + } + else if (body instanceof Uint8Array) { + this.#body = body; + this.#bodyType = "application/octet-stream"; + } + else if (typeof (body) === "object") { + this.#body = (0,utf8/* toUtf8Bytes */.YW)(JSON.stringify(body)); + this.#bodyType = "application/json"; + } + else { + throw new Error("invalid body"); + } + } + /** + * Returns true if the request has a body. + */ + hasBody() { + return (this.#body != null); + } + /** + * The HTTP method to use when requesting the URI. If no method + * has been explicitly set, then ``GET`` is used if the body is + * null and ``POST`` otherwise. + */ + get method() { + if (this.#method) { + return this.#method; + } + if (this.hasBody()) { + return "POST"; + } + return "GET"; + } + set method(method) { + if (method == null) { + method = ""; + } + this.#method = String(method).toUpperCase(); + } + /** + * The headers that will be used when requesting the URI. All + * keys are lower-case. + * + * This object is a copy, so any changes will **NOT** be reflected + * in the ``FetchRequest``. + * + * To set a header entry, use the ``setHeader`` method. + */ + get headers() { + const headers = Object.assign({}, this.#headers); + if (this.#creds) { + headers["authorization"] = `Basic ${encodeBase64((0,utf8/* toUtf8Bytes */.YW)(this.#creds))}`; + } + ; + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && this.#bodyType) { + headers["content-type"] = this.#bodyType; + } + if (this.body) { + headers["content-length"] = String(this.body.length); + } + return headers; + } + /** + * Get the header for %%key%%, ignoring case. + */ + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + /** + * Set the header for %%key%% to %%value%%. All values are coerced + * to a string. + */ + setHeader(key, value) { + this.#headers[String(key).toLowerCase()] = String(value); + } + /** + * Clear all headers, resetting all intrinsic headers. + */ + clearHeaders() { + this.#headers = {}; + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The value that will be sent for the ``Authorization`` header. + * + * To set the credentials, use the ``setCredentials`` method. + */ + get credentials() { + return this.#creds || null; + } + /** + * Sets an ``Authorization`` for %%username%% with %%password%%. + */ + setCredentials(username, password) { + (0,errors/* assertArgument */.MR)(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"); + this.#creds = `${username}:${password}`; + } + /** + * Enable and request gzip-encoded responses. The response will + * automatically be decompressed. //(default: true)// + */ + get allowGzip() { + return this.#gzip; + } + set allowGzip(value) { + this.#gzip = !!value; + } + /** + * Allow ``Authentication`` credentials to be sent over insecure + * channels. //(default: false)// + */ + get allowInsecureAuthentication() { + return !!this.#allowInsecure; + } + set allowInsecureAuthentication(value) { + this.#allowInsecure = !!value; + } + /** + * The timeout (in milliseconds) to wait for a complete response. + * //(default: 5 minutes)// + */ + get timeout() { return this.#timeout; } + set timeout(timeout) { + (0,errors/* assertArgument */.MR)(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + this.#timeout = timeout; + } + /** + * This function is called prior to each request, for example + * during a redirection or retry in case of server throttling. + * + * This offers an opportunity to populate headers or update + * content before sending a request. + */ + get preflightFunc() { + return this.#preflight || null; + } + set preflightFunc(preflight) { + this.#preflight = preflight; + } + /** + * This function is called after each response, offering an + * opportunity to provide client-level throttling or updating + * response data. + * + * Any error thrown in this causes the ``send()`` to throw. + * + * To schedule a retry attempt (assuming the maximum retry limit + * has not been reached), use [[response.throwThrottleError]]. + */ + get processFunc() { + return this.#process || null; + } + set processFunc(process) { + this.#process = process; + } + /** + * This function is called on each retry attempt. + */ + get retryFunc() { + return this.#retry || null; + } + set retryFunc(retry) { + this.#retry = retry; + } + /** + * This function is called to fetch content from HTTP and + * HTTPS URLs and is platform specific (e.g. nodejs vs + * browsers). + * + * This is by default the currently registered global getUrl + * function, which can be changed using [[registerGetUrl]]. + * If this has been set, setting is to ``null`` will cause + * this FetchRequest (and any future clones) to revert back to + * using the currently registered global getUrl function. + * + * Setting this is generally not necessary, but may be useful + * for developers that wish to intercept requests or to + * configurege a proxy or other agent. + */ + get getUrlFunc() { + return this.#getUrlFunc || defaultGetUrlFunc; + } + set getUrlFunc(value) { + this.#getUrlFunc = value; + } + /** + * Create a new FetchRequest instance with default values. + * + * Once created, each property may be set before issuing a + * ``.send()`` to make the request. + */ + constructor(url) { + this.#url = String(url); + this.#allowInsecure = false; + this.#gzip = true; + this.#headers = {}; + this.#method = ""; + this.#timeout = 300000; + this.#throttle = { + slotInterval: SLOT_INTERVAL, + maxAttempts: MAX_ATTEMPTS + }; + this.#getUrlFunc = null; + } + toString() { + return ``; + } + /** + * Update the throttle parameters used to determine maximum + * attempts and exponential-backoff properties. + */ + setThrottleParams(params) { + if (params.slotInterval != null) { + this.#throttle.slotInterval = params.slotInterval; + } + if (params.maxAttempts != null) { + this.#throttle.maxAttempts = params.maxAttempts; + } + } + async #send(attempt, expires, delay, _request, _response) { + if (attempt >= this.#throttle.maxAttempts) { + return _response.makeServerError("exceeded maximum retry limit"); + } + (0,errors/* assert */.vA)(getTime() <= expires, "timeout", "TIMEOUT", { + operation: "request.send", reason: "timeout", request: _request + }); + if (delay > 0) { + await wait(delay); + } + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + // Process any Gateways + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); + if (result instanceof FetchResponse) { + let response = result; + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Ignore throttling + } + } + return response; + } + req = result; + } + // We have a preflight function; update the request + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await this.getUrlFunc(req, checkSignal(_request.#signal)); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); + if (response.statusCode === 301 || response.statusCode === 302) { + // Redirect + try { + const location = response.headers.location || ""; + return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); + } + catch (error) { } + // Things won't get any better on another attempt; abort + return response; + } + else if (response.statusCode === 429) { + // Throttle + if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { + const retryAfter = response.headers["retry-after"]; + let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay = parseInt(retryAfter); + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Throttle + let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + ; + if (error.stall >= 0) { + delay = error.stall; + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + return response; + } + /** + * Resolves to the response by sending the request. + */ + send() { + (0,errors/* assert */.vA)(this.#signal == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); + this.#signal = new FetchCancelSignal(this); + return this.#send(0, getTime() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + /** + * Cancels the inflight response, causing a ``CANCELLED`` + * error to be rejected from the [[send]]. + */ + cancel() { + (0,errors/* assert */.vA)(this.#signal != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); + } + signal(); + } + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location) { + // Redirection; for now we only support absolute locations + const current = this.url.split(":")[0].toLowerCase(); + const target = location.split(":")[0].toLowerCase(); + // Don't allow redirecting: + // - non-GET requests + // - downgrading the security (e.g. https => http) + // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] + (0,errors/* assert */.vA)(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` + }); + // Create a copy of this request, with a new URL + const req = new FetchRequest(location); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + req.#headers = Object.assign({}, this.#headers); + if (this.#body) { + req.#body = new Uint8Array(this.#body); + } + req.#bodyType = this.#bodyType; + // Do not forward credentials unless on the same domain; only absolute + //req.allowInsecure = false; + // paths are currently supported; may want a way to specify to forward? + //setStore(req.#props, "creds", getStore(this.#pros, "creds")); + return req; + } + /** + * Create a new copy of this request. + */ + clone() { + const clone = new FetchRequest(this.url); + // Preserve "default method" (i.e. null) + clone.#method = this.#method; + // Preserve "default body" with type, copying the Uint8Array is present + if (this.#body) { + clone.#body = this.#body; + } + clone.#bodyType = this.#bodyType; + // Preserve "default headers" + clone.#headers = Object.assign({}, this.#headers); + // Credentials is readonly, so we copy internally + clone.#creds = this.#creds; + if (this.allowGzip) { + clone.allowGzip = true; + } + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; + } + clone.#preflight = this.#preflight; + clone.#process = this.#process; + clone.#retry = this.#retry; + clone.#throttle = Object.assign({}, this.#throttle); + clone.#getUrlFunc = this.#getUrlFunc; + return clone; + } + /** + * Locks all static configuration for gateways and FetchGetUrlFunc + * registration. + */ + static lockConfig() { + locked = true; + } + /** + * Get the current Gateway function for %%scheme%%. + */ + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + /** + * Use the %%func%% when fetching URIs using %%scheme%%. + * + * This method affects all requests globally. + * + * If [[lockConfig]] has been called, no change is made and this + * throws. + */ + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); + } + if (locked) { + throw new Error("gateways locked"); + } + Gateways[scheme] = func; + } + /** + * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests. + * + * This method affects all requests globally. + * + * If [[lockConfig]] has been called, no change is made and this + * throws. + */ + static registerGetUrl(getUrl) { + if (locked) { + throw new Error("gateways locked"); + } + defaultGetUrlFunc = getUrl; + } + /** + * Creates a getUrl function that fetches content from HTTP and + * HTTPS URLs. + * + * The available %%options%% are dependent on the platform + * implementation of the default getUrl function. + * + * This is not generally something that is needed, but is useful + * when trying to customize simple behaviour when fetching HTTP + * content. + */ + static createGetUrlFunc(options) { + return createGetUrl(options); + } + /** + * Creates a function that can "fetch" data URIs. + * + * Note that this is automatically done internally to support + * data URIs, so it is not necessary to register it. + * + * This is not generally something that is needed, but may + * be useful in a wrapper to perfom custom data URI functionality. + */ + static createDataGateway() { + return dataGatewayFunc; + } + /** + * Creates a function that will fetch IPFS (unvalidated) from + * a custom gateway baseUrl. + * + * The default IPFS gateway used internally is + * ``"https:/\/gateway.ipfs.io/ipfs/"``. + */ + static createIpfsGatewayFunc(baseUrl) { + return getIpfsGatewayFunc(baseUrl); + } +} +; +/** + * The response for a FetchRequest. + */ +class FetchResponse { + #statusCode; + #statusMessage; + #headers; + #body; + #request; + #error; + toString() { + return ``; + } + /** + * The response status code. + */ + get statusCode() { return this.#statusCode; } + /** + * The response status message. + */ + get statusMessage() { return this.#statusMessage; } + /** + * The response headers. All keys are lower-case. + */ + get headers() { return Object.assign({}, this.#headers); } + /** + * The response body, or ``null`` if there was no body. + */ + get body() { + return (this.#body == null) ? null : new Uint8Array(this.#body); + } + /** + * The response body as a UTF-8 encoded string, or the empty + * string (i.e. ``""``) if there was no body. + * + * An error is thrown if the body is invalid UTF-8 data. + */ + get bodyText() { + try { + return (this.#body == null) ? "" : (0,utf8/* toUtf8String */._v)(this.#body); + } + catch (error) { + (0,errors/* assert */.vA)(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", info: { response: this } + }); + } + } + /** + * The response body, decoded as JSON. + * + * An error is thrown if the body is invalid JSON-encoded data + * or if there was no body. + */ + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } + catch (error) { + (0,errors/* assert */.vA)(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", info: { response: this } + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + constructor(statusCode, statusMessage, headers, body, request) { + this.#statusCode = statusCode; + this.#statusMessage = statusMessage; + this.#headers = Object.keys(headers).reduce((accum, k) => { + accum[k.toLowerCase()] = String(headers[k]); + return accum; + }, {}); + this.#body = ((body == null) ? null : new Uint8Array(body)); + this.#request = (request || null); + this.#error = { message: "" }; + } + /** + * Return a Response with matching headers and body, but with + * an error status code (i.e. 599) and %%message%% with an + * optional %%error%%. + */ + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } + else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); + response.#error = { message, error }; + return response; + } + /** + * If called within a [request.processFunc](FetchRequest-processFunc) + * call, causes the request to retry as if throttled for %%stall%% + * milliseconds. + */ + throwThrottleError(message, stall) { + if (stall == null) { + stall = -1; + } + else { + (0,errors/* assertArgument */.MR)(Number.isInteger(stall) && stall >= 0, "invalid stall timeout", "stall", stall); + } + const error = new Error(message || "throttling requests"); + (0,properties/* defineProperties */.n)(error, { stall, throttle: true }); + throw error; + } + /** + * Get the header value for %%key%%, ignoring case. + */ + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + /** + * Returns true if the response has a body. + */ + hasBody() { + return (this.#body != null); + } + /** + * The request made for this response. + */ + get request() { return this.#request; } + /** + * Returns true if this response was a success statusCode. + */ + ok() { + return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300); + } + /** + * Throws a ``SERVER_ERROR`` if this response is not ok. + */ + assertOk() { + if (this.ok()) { + return; + } + let { message, error } = this.#error; + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + let requestUrl = null; + if (this.request) { + requestUrl = this.request.url; + } + let responseBody = null; + try { + if (this.#body) { + responseBody = (0,utf8/* toUtf8String */._v)(this.#body); + } + } + catch (e) { } + (0,errors/* assert */.vA)(false, message, "SERVER_ERROR", { + request: (this.request || "unknown request"), response: this, error, + info: { + requestUrl, responseBody, + responseStatus: `${this.statusCode} ${this.statusMessage}` + } + }); + } +} +function getTime() { return (new Date()).getTime(); } +function unpercent(value) { + return (0,utf8/* toUtf8Bytes */.YW)(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { + return String.fromCharCode(parseInt(code, 16)); + })); +} +function wait(delay) { + return new Promise((resolve) => setTimeout(resolve, delay)); +} +//# sourceMappingURL=fetch.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/units.js + 1 modules +var units = __webpack_require__(99770); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/abi-coder.js + 10 modules +var abi_coder = __webpack_require__(35273); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/address.js +var address_address = __webpack_require__(30031); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/checks.js +var checks = __webpack_require__(41442); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/keccak.js + 1 modules +var keccak = __webpack_require__(15539); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/hash/id.js +var id = __webpack_require__(38264); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/hash/typed-data.js +//import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer"; + + + + + +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +; +; +function hexPadRight(value) { + const bytes = (0,utils_data/* getBytes */.q5)(value); + const padOffset = bytes.length % 32; + if (padOffset) { + return (0,utils_data/* concat */.xW)([bytes, padding.slice(padOffset)]); + } + return (0,utils_data/* hexlify */.c$)(bytes); +} +const hexTrue = (0,maths/* toBeHex */.up)(BN_1, 32); +const hexFalse = (0,maths/* toBeHex */.up)(BN_0, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", "version", "chainId", "verifyingContract", "salt" +]; +function checkString(key) { + return function (value) { + (0,errors/* assertArgument */.MR)(typeof (value) === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function (_value) { + const value = (0,maths/* getBigInt */.Ab)(_value, "domain.chainId"); + (0,errors/* assertArgument */.MR)(value >= 0, "invalid chain ID", "domain.chainId", _value); + if (Number.isSafeInteger(value)) { + return Number(value); + } + return (0,maths/* toQuantity */.nD)(value); + }, + verifyingContract: function (value) { + try { + return (0,address_address/* getAddress */.b)(value).toLowerCase(); + } + catch (error) { } + (0,errors/* assertArgument */.MR)(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function (value) { + const bytes = (0,utils_data/* getBytes */.q5)(value, "domain.salt"); + (0,errors/* assertArgument */.MR)(bytes.length === 32, `invalid domain value "salt"`, "domain.salt", value); + return (0,utils_data/* hexlify */.c$)(bytes); + } +}; +function getBaseEncoder(type) { + // intXX and uintXX + { + const match = type.match(/^(u?)int(\d+)$/); + if (match) { + const signed = (match[1] === ""); + const width = parseInt(match[2]); + (0,errors/* assertArgument */.MR)(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type); + const boundsUpper = (0,maths/* mask */.dK)(BN_MAX_UINT256, signed ? (width - 1) : width); + const boundsLower = signed ? ((boundsUpper + BN_1) * BN__1) : BN_0; + return function (_value) { + const value = (0,maths/* getBigInt */.Ab)(_value, "value"); + (0,errors/* assertArgument */.MR)(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value); + return (0,maths/* toBeHex */.up)(signed ? (0,maths/* toTwos */.JJ)(value, 256) : value, 32); + }; + } + } + // bytesXX + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + (0,errors/* assertArgument */.MR)(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type); + return function (value) { + const bytes = (0,utils_data/* getBytes */.q5)(value); + (0,errors/* assertArgument */.MR)(bytes.length === width, `invalid length for ${type}`, "value", value); + return hexPadRight(value); + }; + } + } + switch (type) { + case "address": return function (value) { + return (0,utils_data/* zeroPadValue */.nx)((0,address_address/* getAddress */.b)(value), 32); + }; + case "bool": return function (value) { + return ((!value) ? hexFalse : hexTrue); + }; + case "bytes": return function (value) { + return (0,keccak/* keccak256 */.S)(value); + }; + case "string": return function (value) { + return (0,id.id)(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`; +} +// foo[][3] => { base: "foo", index: "[][3]", array: { +// base: "foo", prefix: "foo[]", count: 3 } } +function splitArray(type) { + const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/); + if (match) { + return { + base: match[1], + index: (match[2] + match[4]), + array: { + base: match[1], + prefix: (match[1] + match[2]), + count: (match[5] ? parseInt(match[5]) : -1), + } + }; + } + return { base: type }; +} +/** + * A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads + * for signed typed data. + * + * This is useful for those that wish to compute various components of a + * typed data hash, primary types, or sub-components, but generally the + * higher level [[Signer-signTypedData]] is more useful. + */ +class TypedDataEncoder { + /** + * The primary type for the structured [[types]]. + * + * This is derived automatically from the [[types]], since no + * recursion is possible, once the DAG for the types is consturcted + * internally, the primary type must be the only remaining type with + * no parent nodes. + */ + primaryType; + #types; + /** + * The types. + */ + get types() { + return JSON.parse(this.#types); + } + #fullTypes; + #encoderCache; + /** + * Create a new **TypedDataEncoder** for %%types%%. + * + * This performs all necessary checking that types are valid and + * do not violate the [[link-eip-712]] structural constraints as + * well as computes the [[primaryType]]. + */ + constructor(_types) { + this.#fullTypes = new Map(); + this.#encoderCache = new Map(); + // Link struct types to their direct child structs + const links = new Map(); + // Link structs to structs which contain them as a child + const parents = new Map(); + // Link all subtypes within a given struct + const subtypes = new Map(); + const types = {}; + Object.keys(_types).forEach((type) => { + types[type] = _types[type].map(({ name, type }) => { + // Normalize the base type (unless name conflict) + let { base, index } = splitArray(type); + if (base === "int" && !_types["int"]) { + base = "int256"; + } + if (base === "uint" && !_types["uint"]) { + base = "uint256"; + } + return { name, type: (base + (index || "")) }; + }); + links.set(type, new Set()); + parents.set(type, []); + subtypes.set(type, new Set()); + }); + this.#types = JSON.stringify(types); + for (const name in types) { + const uniqueNames = new Set(); + for (const field of types[name]) { + // Check each field has a unique name + (0,errors/* assertArgument */.MR)(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", _types); + uniqueNames.add(field.name); + // Get the base type (drop any array specifiers) + const baseType = splitArray(field.type).base; + (0,errors/* assertArgument */.MR)(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types); + // Is this a base encoding type? + const encoder = getBaseEncoder(baseType); + if (encoder) { + continue; + } + (0,errors/* assertArgument */.MR)(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types); + // Add linkage + parents.get(baseType).push(name); + links.get(name).add(baseType); + } + } + // Deduce the primary type + const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0)); + (0,errors/* assertArgument */.MR)(primaryTypes.length !== 0, "missing primary type", "types", _types); + (0,errors/* assertArgument */.MR)(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", _types); + (0,properties/* defineProperties */.n)(this, { primaryType: primaryTypes[0] }); + // Check for circular type references + function checkCircular(type, found) { + (0,errors/* assertArgument */.MR)(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types); + found.add(type); + for (const child of links.get(type)) { + if (!parents.has(child)) { + continue; + } + // Recursively check children + checkCircular(child, found); + // Mark all ancestors as having this decendant + for (const subtype of found) { + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, new Set()); + // Compute each fully describe type + for (const [name, set] of subtypes) { + const st = Array.from(set); + st.sort(); + this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join("")); + } + } + /** + * Returnthe encoder for the specific %%type%%. + */ + getEncoder(type) { + let encoder = this.#encoderCache.get(type); + if (!encoder) { + encoder = this.#getEncoder(type); + this.#encoderCache.set(type, encoder); + } + return encoder; + } + #getEncoder(type) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + // Array + const array = splitArray(type).array; + if (array) { + const subtype = array.prefix; + const subEncoder = this.getEncoder(subtype); + return (value) => { + (0,errors/* assertArgument */.MR)(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + let result = value.map(subEncoder); + if (this.#fullTypes.has(subtype)) { + result = result.map(keccak/* keccak256 */.S); + } + return (0,keccak/* keccak256 */.S)((0,utils_data/* concat */.xW)(result)); + }; + } + // Struct + const fields = this.types[type]; + if (fields) { + const encodedType = (0,id.id)(this.#fullTypes.get(type)); + return (value) => { + const values = fields.map(({ name, type }) => { + const result = this.getEncoder(type)(value[name]); + if (this.#fullTypes.has(type)) { + return (0,keccak/* keccak256 */.S)(result); + } + return result; + }); + values.unshift(encodedType); + return (0,utils_data/* concat */.xW)(values); + }; + } + (0,errors/* assertArgument */.MR)(false, `unknown type: ${type}`, "type", type); + } + /** + * Return the full type for %%name%%. + */ + encodeType(name) { + const result = this.#fullTypes.get(name); + (0,errors/* assertArgument */.MR)(result, `unknown type: ${JSON.stringify(name)}`, "name", name); + return result; + } + /** + * Return the encoded %%value%% for the %%type%%. + */ + encodeData(type, value) { + return this.getEncoder(type)(value); + } + /** + * Returns the hash of %%value%% for the type of %%name%%. + */ + hashStruct(name, value) { + return (0,keccak/* keccak256 */.S)(this.encodeData(name, value)); + } + /** + * Return the fulled encoded %%value%% for the [[types]]. + */ + encode(value) { + return this.encodeData(this.primaryType, value); + } + /** + * Return the hash of the fully encoded %%value%% for the [[types]]. + */ + hash(value) { + return this.hashStruct(this.primaryType, value); + } + /** + * @_ignore: + */ + _visit(type, value, callback) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + // Array + const array = splitArray(type).array; + if (array) { + (0,errors/* assertArgument */.MR)(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + return value.map((v) => this._visit(array.prefix, v, callback)); + } + // Struct + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type }) => { + accum[name] = this._visit(type, value[name], callback); + return accum; + }, {}); + } + (0,errors/* assertArgument */.MR)(false, `unknown type: ${type}`, "type", type); + } + /** + * Call %%calback%% for each value in %%value%%, passing the type and + * component within %%value%%. + * + * This is useful for replacing addresses or other transformation that + * may be desired on each component, based on its type. + */ + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + /** + * Create a new **TypedDataEncoder** for %%types%%. + */ + static from(types) { + return new TypedDataEncoder(types); + } + /** + * Return the primary type for %%types%%. + */ + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + /** + * Return the hashed struct for %%value%% using %%types%% and %%name%%. + */ + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + /** + * Return the domain hash for %%domain%%. + */ + static hashDomain(domain) { + const domainFields = []; + for (const name in domain) { + if (domain[name] == null) { + continue; + } + const type = domainFieldTypes[name]; + (0,errors/* assertArgument */.MR)(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + domainFields.push({ name, type }); + } + domainFields.sort((a, b) => { + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain); + } + /** + * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. + */ + static encode(domain, types, value) { + return (0,utils_data/* concat */.xW)([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + /** + * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%. + */ + static hash(domain, types, value) { + return (0,keccak/* keccak256 */.S)(TypedDataEncoder.encode(domain, types, value)); + } + // Replaces all address types with ENS names with their looked up address + /** + * Resolves to the value from resolving all addresses in %%value%% for + * %%types%% and the %%domain%%. + */ + static async resolveNames(domain, types, value, resolveName) { + // Make a copy to isolate it from the object passed in + domain = Object.assign({}, domain); + // Allow passing null to ignore value + for (const key in domain) { + if (domain[key] == null) { + delete domain[key]; + } + } + // Look up all ENS names + const ensCache = {}; + // Do we need to look up the domain's verifyingContract? + if (domain.verifyingContract && !(0,utils_data/* isHexString */.Lo)(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + // We are going to use the encoder to visit all the base values + const encoder = TypedDataEncoder.from(types); + // Get a list of all the addresses + encoder.visit(value, (type, value) => { + if (type === "address" && !(0,utils_data/* isHexString */.Lo)(value, 20)) { + ensCache[value] = "0x"; + } + return value; + }); + // Lookup each name + for (const name in ensCache) { + ensCache[name] = await resolveName(name); + } + // Replace the domain verifyingContract if needed + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + // Replace all ENS names with their address + value = encoder.visit(value, (type, value) => { + if (type === "address" && ensCache[value]) { + return ensCache[value]; + } + return value; + }); + return { domain, value }; + } + /** + * Returns the JSON-encoded payload expected by nodes which implement + * the JSON-RPC [[link-eip-712]] method. + */ + static getPayload(domain, types, value) { + // Validate the domain fields + TypedDataEncoder.hashDomain(domain); + // Derive the EIP712Domain Struct reference type + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name) => { + const value = domain[name]; + if (value == null) { + return; + } + domainValues[name] = domainChecks[name](value); + domainTypes.push({ name, type: domainFieldTypes[name] }); + }); + const encoder = TypedDataEncoder.from(types); + // Get the normalized types + types = encoder.types; + const typesWithDomain = Object.assign({}, types); + (0,errors/* assertArgument */.MR)(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types); + typesWithDomain.EIP712Domain = domainTypes; + // Validate the data structures and types + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value) => { + // bytes + if (type.match(/^bytes(\d*)/)) { + return (0,utils_data/* hexlify */.c$)((0,utils_data/* getBytes */.q5)(value)); + } + // uint or int + if (type.match(/^u?int/)) { + return (0,maths/* getBigInt */.Ab)(value).toString(); + } + switch (type) { + case "address": + return value.toLowerCase(); + case "bool": + return !!value; + case "string": + (0,errors/* assertArgument */.MR)(typeof (value) === "string", "invalid string", "value", value); + return value; + } + (0,errors/* assertArgument */.MR)(false, "unsupported type", "type", type); + }) + }; + } +} +/** + * Compute the address used to sign the typed data for the %%signature%%. + */ +function verifyTypedData(domain, types, value, signature) { + return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); +} +//# sourceMappingURL=typed-data.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/transaction/accesslist.js +var accesslist = __webpack_require__(8177); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/constants/addresses.js +var addresses = __webpack_require__(98982); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/contract/contract.js + 1 modules +var contract_contract = __webpack_require__(24391); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/hash/namehash.js + 1 modules +var namehash = __webpack_require__(64563); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/transaction/transaction.js + 1 modules +var transaction = __webpack_require__(79453); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/events.js +var events = __webpack_require__(99381); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/base58.js +/** + * The [Base58 Encoding](link-base58) scheme allows a **numeric** value + * to be encoded as a compact string using a radix of 58 using only + * alpha-numeric characters. Confusingly similar characters are omitted + * (i.e. ``"l0O"``). + * + * Note that Base58 encodes a **numeric** value, not arbitrary bytes, + * since any zero-bytes on the left would get removed. To mitigate this + * issue most schemes that use Base58 choose specific high-order values + * to ensure non-zero prefixes. + * + * @_subsection: api/utils:Base58 Encoding [about-base58] + */ + + + +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for (let i = 0; i < Alphabet.length; i++) { + Lookup[Alphabet[i]] = BigInt(i); + } + } + const result = Lookup[letter]; + (0,errors/* assertArgument */.MR)(result != null, `invalid base58 value`, "letter", letter); + return result; +} +const base58_BN_0 = BigInt(0); +const BN_58 = BigInt(58); +/** + * Encode %%value%% as a Base58-encoded string. + */ +function encodeBase58(_value) { + const bytes = (0,utils_data/* getBytes */.q5)(_value); + let value = (0,maths/* toBigInt */.Dg)(bytes); + let result = ""; + while (value) { + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + // Account for leading padding zeros + for (let i = 0; i < bytes.length; i++) { + if (bytes[i]) { + break; + } + result = Alphabet[0] + result; + } + return result; +} +/** + * Decode the Base58-encoded %%value%%. + */ +function decodeBase58(value) { + let result = base58_BN_0; + for (let i = 0; i < value.length; i++) { + result *= BN_58; + result += getAlpha(value[i]); + } + return result; +} +//# sourceMappingURL=base58.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/ens-resolver.js +/** + * ENS is a service which allows easy-to-remember names to map to + * network addresses. + * + * @_section: api/providers/ens-resolver:ENS Resolver [about-ens-rsolver] + */ + + + + + +// @TODO: This should use the fetch-data:ipfs gateway +// Trim off the ipfs:// prefix and return the default gateway URL +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } + else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } + else { + (0,errors/* assertArgument */.MR)(false, "unsupported IPFS format", "link", link); + } + return `https:/\/gateway.ipfs.io/ipfs/${link}`; +} +; +; +/** + * A provider plugin super-class for processing multicoin address types. + */ +class MulticoinProviderPlugin { + /** + * The name. + */ + name; + /** + * Creates a new **MulticoinProviderPluing** for %%name%%. + */ + constructor(name) { + (0,properties/* defineProperties */.n)(this, { name }); + } + connect(proivder) { + return this; + } + /** + * Returns ``true`` if %%coinType%% is supported by this plugin. + */ + supportsCoinType(coinType) { + return false; + } + /** + * Resovles to the encoded %%address%% for %%coinType%%. + */ + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + /** + * Resovles to the decoded %%data%% for %%coinType%%. + */ + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); + } +} +const BasicMulticoinPluginId = "org.ethers.plugins.provider.BasicMulticoin"; +/** + * A **BasicMulticoinProviderPlugin** provides service for common + * coin types, which do not require additional libraries to encode or + * decode. + */ +class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin { + /** + * Creates a new **BasicMulticoinProviderPlugin**. + */ + constructor() { + super(BasicMulticoinPluginId); + } +} +const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i"); +const matchers = [ + new RegExp("^(https):/\/(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"), +]; +/** + * A connected object to a resolved ENS name resolver, which can be + * used to query additional details. + */ +class EnsResolver { + /** + * The connected provider. + */ + provider; + /** + * The address of the resolver. + */ + address; + /** + * The name this resolver was resolved against. + */ + name; + // For EIP-2544 names, the ancestor that provided the resolver + #supports2544; + #resolver; + constructor(provider, address, name) { + (0,properties/* defineProperties */.n)(this, { provider, address, name }); + this.#supports2544 = null; + this.#resolver = new contract_contract/* Contract */.NZ(address, [ + "function supportsInterface(bytes4) view returns (bool)", + "function resolve(bytes, bytes) view returns (bytes)", + "function addr(bytes32) view returns (address)", + "function addr(bytes32, uint) view returns (bytes)", + "function text(bytes32, string) view returns (string)", + "function contenthash(bytes32) view returns (bytes)", + ], provider); + } + /** + * Resolves to true if the resolver supports wildcard resolution. + */ + async supportsWildcard() { + if (this.#supports2544 == null) { + this.#supports2544 = (async () => { + try { + return await this.#resolver.supportsInterface("0x9061b923"); + } + catch (error) { + // Wildcard resolvers must understand supportsInterface + // and return true. + if ((0,errors/* isError */.bJ)(error, "CALL_EXCEPTION")) { + return false; + } + // Let future attempts try again... + this.#supports2544 = null; + throw error; + } + })(); + } + return await this.#supports2544; + } + async #fetch(funcName, params) { + params = (params || []).slice(); + const iface = this.#resolver.interface; + // The first parameters is always the nodehash + params.unshift((0,namehash/* namehash */.kM)(this.name)); + let fragment = null; + if (await this.supportsWildcard()) { + fragment = iface.getFunction(funcName); + (0,errors/* assert */.vA)(fragment, "missing fragment", "UNKNOWN_ERROR", { + info: { funcName } + }); + params = [ + (0,namehash/* dnsEncode */.Wh)(this.name, 255), + iface.encodeFunctionData(fragment, params) + ]; + funcName = "resolve(bytes,bytes)"; + } + params.push({ + enableCcipRead: true + }); + try { + const result = await this.#resolver[funcName](...params); + if (fragment) { + return iface.decodeFunctionResult(fragment, result)[0]; + } + return result; + } + catch (error) { + if (!(0,errors/* isError */.bJ)(error, "CALL_EXCEPTION")) { + throw error; + } + } + return null; + } + /** + * Resolves to the address for %%coinType%% or null if the + * provided %%coinType%% has not been configured. + */ + async getAddress(coinType) { + if (coinType == null) { + coinType = 60; + } + if (coinType === 60) { + try { + const result = await this.#fetch("addr(bytes32)"); + // No address + if (result == null || result === addresses/* ZeroAddress */.j) { + return null; + } + return result; + } + catch (error) { + if ((0,errors/* isError */.bJ)(error, "CALL_EXCEPTION")) { + return null; + } + throw error; + } + } + // Try decoding its EVM canonical chain as an EVM chain address first + if (coinType >= 0 && coinType < 0x80000000) { + let ethCoinType = coinType + 0x80000000; + const data = await this.#fetch("addr(bytes32,uint)", [ethCoinType]); + if ((0,utils_data/* isHexString */.Lo)(data, 20)) { + return (0,address_address/* getAddress */.b)(data); + } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins) { + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; + } + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; + } + } + if (coinPlugin == null) { + return null; + } + // keccak256("addr(bytes32,uint256") + const data = await this.#fetch("addr(bytes32,uint)", [coinType]); + // No address + if (data == null || data === "0x") { + return null; + } + // Compute the address + const address = await coinPlugin.decodeAddress(coinType, data); + if (address != null) { + return address; + } + (0,errors/* assert */.vA)(false, `invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { coinType, data } + }); + } + /** + * Resolves to the EIP-634 text record for %%key%%, or ``null`` + * if unconfigured. + */ + async getText(key) { + const data = await this.#fetch("text(bytes32,string)", [key]); + if (data == null || data === "0x") { + return null; + } + return data; + } + /** + * Rsolves to the content-hash or ``null`` if unconfigured. + */ + async getContentHash() { + // keccak256("contenthash()") + const data = await this.#fetch("contenthash(bytes32)"); + // No contenthash + if (data == null || data === "0x") { + return null; + } + // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key) + const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`; + } + } + // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32) + const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz:/\/${swarm[1]}`; + } + (0,errors/* assert */.vA)(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { data } + }); + } + /** + * Resolves to the avatar url or ``null`` if the avatar is either + * unconfigured or incorrectly configured (e.g. references an NFT + * not owned by the address). + * + * If diagnosing issues with configurations, the [[_getAvatar]] + * method may be useful. + */ + async getAvatar() { + const avatar = await this._getAvatar(); + return avatar.url; + } + /** + * When resolving an avatar, there are many steps involved, such + * fetching metadata and possibly validating ownership of an + * NFT. + * + * This method can be used to examine each step and the value it + * was working from. + */ + async _getAvatar() { + const linkage = [{ type: "name", value: this.name }]; + try { + // test data for ricmoo.eth + //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233"; + const avatar = await this.getText("avatar"); + if (avatar == null) { + linkage.push({ type: "!avatar", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "avatar", value: avatar }); + for (let i = 0; i < matchers.length; i++) { + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch (scheme) { + case "https": + case "data": + linkage.push({ type: "url", value: avatar }); + return { linkage, url: avatar }; + case "ipfs": { + const url = getIpfsLink(avatar); + linkage.push({ type: "ipfs", value: avatar }); + linkage.push({ type: "url", value: url }); + return { linkage, url }; + } + case "erc721": + case "erc1155": { + // Depending on the ERC type, use tokenURI(uint256) or url(uint256) + const selector = (scheme === "erc721") ? "tokenURI(uint256)" : "uri(uint256)"; + linkage.push({ type: scheme, value: avatar }); + // The owner of this name + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ type: "!owner", value: "" }); + return { url: null, linkage }; + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") }); + return { url: null, linkage }; + } + const tokenId = comps[1]; + const contract = new contract_contract/* Contract */.NZ(comps[0], [ + // ERC-721 + "function tokenURI(uint) view returns (string)", + "function ownerOf(uint) view returns (address)", + // ERC-1155 + "function uri(uint) view returns (string)", + "function balanceOf(address, uint256) view returns (uint)" + ], this.provider); + // Check that this account owns the token + if (scheme === "erc721") { + const tokenOwner = await contract.ownerOf(tokenId); + if (owner !== tokenOwner) { + linkage.push({ type: "!owner", value: tokenOwner }); + return { url: null, linkage }; + } + linkage.push({ type: "owner", value: tokenOwner }); + } + else if (scheme === "erc1155") { + const balance = await contract.balanceOf(owner, tokenId); + if (!balance) { + linkage.push({ type: "!balance", value: "0" }); + return { url: null, linkage }; + } + linkage.push({ type: "balance", value: balance.toString() }); + } + // Call the token contract for the metadata URL + let metadataUrl = await contract[selector](tokenId); + if (metadataUrl == null || metadataUrl === "0x") { + linkage.push({ type: "!metadata-url", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "metadata-url-base", value: metadataUrl }); + // ERC-1155 allows a generic {id} in the URL + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", (0,maths/* toBeHex */.up)(tokenId, 32).substring(2)); + linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); + } + // Transform IPFS metadata links + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ type: "metadata-url", value: metadataUrl }); + // Get the token metadata + let metadata = {}; + const response = await (new FetchRequest(metadataUrl)).send(); + response.assertOk(); + try { + metadata = response.bodyJson; + } + catch (error) { + try { + linkage.push({ type: "!metadata", value: response.bodyText }); + } + catch (error) { + const bytes = response.body; + if (bytes) { + linkage.push({ type: "!metadata", value: (0,utils_data/* hexlify */.c$)(bytes) }); + } + return { url: null, linkage }; + } + return { url: null, linkage }; + } + if (!metadata) { + linkage.push({ type: "!metadata", value: "" }); + return { url: null, linkage }; + } + linkage.push({ type: "metadata", value: JSON.stringify(metadata) }); + // Pull the image URL out + let imageUrl = metadata.image; + if (typeof (imageUrl) !== "string") { + linkage.push({ type: "!imageUrl", value: "" }); + return { url: null, linkage }; + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) { + // Allow + } + else { + // Transform IPFS link to gateway + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); + return { url: null, linkage }; + } + linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ type: "url", value: imageUrl }); + return { linkage, url: imageUrl }; + } + } + } + } + catch (error) { } + return { linkage, url: null }; + } + static async getEnsAddress(provider) { + const network = await provider.getNetwork(); + const ensPlugin = network.getPlugin("org.ethers.plugins.network.Ens"); + // No ENS... + (0,errors/* assert */.vA)(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getEnsAddress", info: { network } + }); + return ensPlugin.address; + } + static async #getResolver(provider, name) { + const ensAddr = await EnsResolver.getEnsAddress(provider); + try { + const contract = new contract_contract/* Contract */.NZ(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], provider); + const addr = await contract.resolver((0,namehash/* namehash */.kM)(name), { + enableCcipRead: true + }); + if (addr === addresses/* ZeroAddress */.j) { + return null; + } + return addr; + } + catch (error) { + // ENS registry cannot throw errors on resolver(bytes32), + // so probably a link error + throw error; + } + return null; + } + /** + * Resolve to the ENS resolver for %%name%% using %%provider%% or + * ``null`` if unconfigured. + */ + static async fromName(provider, name) { + let currentName = name; + while (true) { + if (currentName === "" || currentName === ".") { + return null; + } + // Optimization since the eth node cannot change and does + // not have a wildcard resolver + if (name !== "eth" && currentName === "eth") { + return null; + } + // Check the current node for a resolver + const addr = await EnsResolver.#getResolver(provider, currentName); + // Found a resolver! + if (addr != null) { + const resolver = new EnsResolver(provider, addr, name); + // Legacy resolver found, using EIP-2544 so it isn't safe to use + if (currentName !== name && !(await resolver.supportsWildcard())) { + return null; + } + return resolver; + } + // Get the parent node + currentName = currentName.split(".").slice(1).join("."); + } + } +} +//# sourceMappingURL=ens-resolver.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/rlp-encode.js +var rlp_encode = __webpack_require__(65735); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/address/contract-address.js + + + +// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed +/** + * Returns the address that would result from a ``CREATE`` for %%tx%%. + * + * This can be used to compute the address a contract will be + * deployed to by an EOA when sending a deployment transaction (i.e. + * when the ``to`` address is ``null``). + * + * This can also be used to compute the address a contract will be + * deployed to by a contract, by using the contract's address as the + * ``to`` and the contract's nonce. + * + * @example + * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; + * nonce = 5; + * + * getCreateAddress({ from, nonce }); + * //_result: + */ +function getCreateAddress(tx) { + const from = (0,address_address/* getAddress */.b)(tx.from); + const nonce = (0,maths/* getBigInt */.Ab)(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } + else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; + } + else { + nonceHex = "0x" + nonceHex; + } + return (0,address_address/* getAddress */.b)((0,utils_data/* dataSlice */.ZG)((0,keccak/* keccak256 */.S)((0,rlp_encode/* encodeRlp */.R)([from, nonceHex])), 12)); +} +/** + * Returns the address that would result from a ``CREATE2`` operation + * with the given %%from%%, %%salt%% and %%initCodeHash%%. + * + * To compute the %%initCodeHash%% from a contract's init code, use + * the [[keccak256]] function. + * + * For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]]. + * + * @example + * // The address of the contract + * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72" + * + * // The salt + * salt = id("HelloWorld") + * + * // The hash of the initCode + * initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3"; + * initCodeHash = keccak256(initCode) + * + * getCreate2Address(from, salt, initCodeHash) + * //_result: + */ +function getCreate2Address(_from, _salt, _initCodeHash) { + const from = getAddress(_from); + const salt = getBytes(_salt, "salt"); + const initCodeHash = getBytes(_initCodeHash, "initCodeHash"); + assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt); + assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12)); +} +//# sourceMappingURL=contract-address.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/signature.js + 1 modules +var signature = __webpack_require__(20260); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/format.js +/** + * @_ignore + */ + + + + +const format_BN_0 = BigInt(0); +function allowNull(format, nullValue) { + return (function (value) { + if (value == null) { + return nullValue; + } + return format(value); + }); +} +function arrayOf(format, allowNull) { + return ((array) => { + if (allowNull && array == null) { + return null; + } + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i) => format(i)); + }); +} +// Requires an object which matches a fleet of other formatters +// Any FormatFunc may return `undefined` to have the value omitted +// from the result object. Calls preserve `this`. +function object(format, altNames) { + return ((value) => { + const result = {}; + for (const key in format) { + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]) { + if (altKey in value) { + srcKey = altKey; + break; + } + } + } + try { + const nv = format[key](value[srcKey]); + if (nv !== undefined) { + result[key] = nv; + } + } + catch (error) { + const message = (error instanceof Error) ? error.message : "not-an-error"; + (0,errors/* assert */.vA)(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { value }); + } + } + return result; + }); +} +function formatBoolean(value) { + switch (value) { + case true: + case "true": + return true; + case false: + case "false": + return false; + } + (0,errors/* assertArgument */.MR)(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value); +} +function formatData(value) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isHexString */.Lo)(value, true), "invalid data", "value", value); + return value; +} +function formatHash(value) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isHexString */.Lo)(value, 32), "invalid hash", "value", value); + return value; +} +function formatUint256(value) { + if (!isHexString(value)) { + throw new Error("invalid uint256"); + } + return zeroPadValue(value, 32); +} +const _formatLog = object({ + address: address_address/* getAddress */.b, + blockHash: formatHash, + blockNumber: maths/* getNumber */.WZ, + data: formatData, + index: maths/* getNumber */.WZ, + removed: allowNull(formatBoolean, false), + topics: arrayOf(formatHash), + transactionHash: formatHash, + transactionIndex: maths/* getNumber */.WZ, +}, { + index: ["logIndex"] +}); +function formatLog(value) { + return _formatLog(value); +} +const _formatBlock = object({ + hash: allowNull(formatHash), + parentHash: formatHash, + parentBeaconBlockRoot: allowNull(formatHash, null), + number: maths/* getNumber */.WZ, + timestamp: maths/* getNumber */.WZ, + nonce: allowNull(formatData), + difficulty: maths/* getBigInt */.Ab, + gasLimit: maths/* getBigInt */.Ab, + gasUsed: maths/* getBigInt */.Ab, + stateRoot: allowNull(formatHash, null), + receiptsRoot: allowNull(formatHash, null), + blobGasUsed: allowNull(maths/* getBigInt */.Ab, null), + excessBlobGas: allowNull(maths/* getBigInt */.Ab, null), + miner: allowNull(address_address/* getAddress */.b), + prevRandao: allowNull(formatHash, null), + extraData: formatData, + baseFeePerGas: allowNull(maths/* getBigInt */.Ab) +}, { + prevRandao: ["mixHash"] +}); +function formatBlock(value) { + const result = _formatBlock(value); + result.transactions = value.transactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return formatTransactionResponse(tx); + }); + return result; +} +const _formatReceiptLog = object({ + transactionIndex: maths/* getNumber */.WZ, + blockNumber: maths/* getNumber */.WZ, + transactionHash: formatHash, + address: address_address/* getAddress */.b, + topics: arrayOf(formatHash), + data: formatData, + index: maths/* getNumber */.WZ, + blockHash: formatHash, +}, { + index: ["logIndex"] +}); +function formatReceiptLog(value) { + return _formatReceiptLog(value); +} +const _formatTransactionReceipt = object({ + to: allowNull(address_address/* getAddress */.b, null), + from: allowNull(address_address/* getAddress */.b, null), + contractAddress: allowNull(address_address/* getAddress */.b, null), + // should be allowNull(hash), but broken-EIP-658 support is handled in receipt + index: maths/* getNumber */.WZ, + root: allowNull(utils_data/* hexlify */.c$), + gasUsed: maths/* getBigInt */.Ab, + blobGasUsed: allowNull(maths/* getBigInt */.Ab, null), + logsBloom: allowNull(formatData), + blockHash: formatHash, + hash: formatHash, + logs: arrayOf(formatReceiptLog), + blockNumber: maths/* getNumber */.WZ, + //confirmations: allowNull(getNumber, null), + cumulativeGasUsed: maths/* getBigInt */.Ab, + effectiveGasPrice: allowNull(maths/* getBigInt */.Ab), + blobGasPrice: allowNull(maths/* getBigInt */.Ab, null), + status: allowNull(maths/* getNumber */.WZ), + type: allowNull(maths/* getNumber */.WZ, 0) +}, { + effectiveGasPrice: ["gasPrice"], + hash: ["transactionHash"], + index: ["transactionIndex"], +}); +function formatTransactionReceipt(value) { + return _formatTransactionReceipt(value); +} +function formatTransactionResponse(value) { + // Some clients (TestRPC) do strange things like return 0x0 for the + // 0 address; correct this to be a real address + if (value.to && (0,maths/* getBigInt */.Ab)(value.to) === format_BN_0) { + value.to = "0x0000000000000000000000000000000000000000"; + } + const result = object({ + hash: formatHash, + // Some nodes do not return this, usually test nodes (like Ganache) + index: allowNull(maths/* getNumber */.WZ, undefined), + type: (value) => { + if (value === "0x" || value == null) { + return 0; + } + return (0,maths/* getNumber */.WZ)(value); + }, + accessList: allowNull(accesslist/* accessListify */.$, null), + blobVersionedHashes: allowNull(arrayOf(formatHash, true), null), + blockHash: allowNull(formatHash, null), + blockNumber: allowNull(maths/* getNumber */.WZ, null), + transactionIndex: allowNull(maths/* getNumber */.WZ, null), + from: address_address/* getAddress */.b, + // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set + gasPrice: allowNull(maths/* getBigInt */.Ab), + maxPriorityFeePerGas: allowNull(maths/* getBigInt */.Ab), + maxFeePerGas: allowNull(maths/* getBigInt */.Ab), + maxFeePerBlobGas: allowNull(maths/* getBigInt */.Ab, null), + gasLimit: maths/* getBigInt */.Ab, + to: allowNull(address_address/* getAddress */.b, null), + value: maths/* getBigInt */.Ab, + nonce: maths/* getNumber */.WZ, + data: formatData, + creates: allowNull(address_address/* getAddress */.b, null), + chainId: allowNull(maths/* getBigInt */.Ab, null) + }, { + data: ["input"], + gasLimit: ["gas"], + index: ["transactionIndex"] + })(value); + // If to and creates are empty, populate the creates from the value + if (result.to == null && result.creates == null) { + result.creates = getCreateAddress(result); + } + // @TODO: Check fee data + // Add an access list to supported transaction types + if ((value.type === 1 || value.type === 2) && value.accessList == null) { + result.accessList = []; + } + // Compute the signature + if (value.signature) { + result.signature = signature/* Signature */.t.from(value.signature); + } + else { + result.signature = signature/* Signature */.t.from(value); + } + // Some backends omit ChainId on legacy transactions, but we can compute it + if (result.chainId == null) { + const chainId = result.signature.legacyChainId; + if (chainId != null) { + result.chainId = chainId; + } + } + // @TODO: check chainID + /* + if (value.chainId != null) { + let chainId = value.chainId; + + if (isHexString(chainId)) { + chainId = BigNumber.from(chainId).toNumber(); + } + + result.chainId = chainId; + + } else { + let chainId = value.networkId; + + // geth-etc returns chainId + if (chainId == null && result.v == null) { + chainId = value.chainId; + } + + if (isHexString(chainId)) { + chainId = BigNumber.from(chainId).toNumber(); + } + + if (typeof(chainId) !== "number" && result.v != null) { + chainId = (result.v - 35) / 2; + if (chainId < 0) { chainId = 0; } + chainId = parseInt(chainId); + } + + if (typeof(chainId) !== "number") { chainId = 0; } + + result.chainId = chainId; + } + */ + // 0x0000... should actually be null + if (result.blockHash && (0,maths/* getBigInt */.Ab)(result.blockHash) === format_BN_0) { + result.blockHash = null; + } + return result; +} +//# sourceMappingURL=format.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/network.js +/** + * A **Network** encapsulates the various properties required to + * interact with a specific chain. + * + * @_subsection: api/providers:Networks [networks] + */ + + + +/* * * * +// Networks which operation against an L2 can use this plugin to +// specify how to access L1, for the purpose of resolving ENS, +// for example. +export class LayerOneConnectionPlugin extends NetworkPlugin { + readonly provider!: Provider; +// @TODO: Rename to ChainAccess and allow for connecting to any chain + constructor(provider: Provider) { + super("org.ethers.plugins.layer-one-connection"); + defineProperties(this, { provider }); + } + + clone(): LayerOneConnectionPlugin { + return new LayerOneConnectionPlugin(this.provider); + } +} +*/ +const Networks = new Map(); +/** + * A **Network** provides access to a chain's properties and allows + * for plug-ins to extend functionality. + */ +class Network { + #name; + #chainId; + #plugins; + /** + * Creates a new **Network** for %%name%% and %%chainId%%. + */ + constructor(name, chainId) { + this.#name = name; + this.#chainId = (0,maths/* getBigInt */.Ab)(chainId); + this.#plugins = new Map(); + } + /** + * Returns a JSON-compatible representation of a Network. + */ + toJSON() { + return { name: this.name, chainId: String(this.chainId) }; + } + /** + * The network common name. + * + * This is the canonical name, as networks migh have multiple + * names. + */ + get name() { return this.#name; } + set name(value) { this.#name = value; } + /** + * The network chain ID. + */ + get chainId() { return this.#chainId; } + set chainId(value) { this.#chainId = (0,maths/* getBigInt */.Ab)(value, "chainId"); } + /** + * Returns true if %%other%% matches this network. Any chain ID + * must match, and if no chain ID is present, the name must match. + * + * This method does not currently check for additional properties, + * such as ENS address or plug-in compatibility. + */ + matches(other) { + if (other == null) { + return false; + } + if (typeof (other) === "string") { + try { + return (this.chainId === (0,maths/* getBigInt */.Ab)(other)); + } + catch (error) { } + return (this.name === other); + } + if (typeof (other) === "number" || typeof (other) === "bigint") { + try { + return (this.chainId === (0,maths/* getBigInt */.Ab)(other)); + } + catch (error) { } + return false; + } + if (typeof (other) === "object") { + if (other.chainId != null) { + try { + return (this.chainId === (0,maths/* getBigInt */.Ab)(other.chainId)); + } + catch (error) { } + return false; + } + if (other.name != null) { + return (this.name === other.name); + } + return false; + } + return false; + } + /** + * Returns the list of plugins currently attached to this Network. + */ + get plugins() { + return Array.from(this.#plugins.values()); + } + /** + * Attach a new %%plugin%% to this Network. The network name + * must be unique, excluding any fragment. + */ + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.clone()); + return this; + } + /** + * Return the plugin, if any, matching %%name%% exactly. Plugins + * with fragments will not be returned unless %%name%% includes + * a fragment. + */ + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + /** + * Gets a list of all plugins that match %%name%%, with otr without + * a fragment. + */ + getPlugins(basename) { + return (this.plugins.filter((p) => (p.name.split("#")[0] === basename))); + } + /** + * Create a copy of this Network. + */ + clone() { + const clone = new Network(this.name, this.chainId); + this.plugins.forEach((plugin) => { + clone.attachPlugin(plugin.clone()); + }); + return clone; + } + /** + * Compute the intrinsic gas required for a transaction. + * + * A GasCostPlugin can be attached to override the default + * values. + */ + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || (new GasCostPlugin()); + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for (let i = 2; i < tx.data.length; i += 2) { + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; + } + else { + gas += costs.txDataNonzero; + } + } + } + if (tx.accessList) { + const accessList = (0,accesslist/* accessListify */.$)(tx.accessList); + for (const addr in accessList) { + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; + } + } + return gas; + } + /** + * Returns a new Network for the %%network%% name or chainId. + */ + static from(network) { + injectCommonNetworks(); + // Default network + if (network == null) { + return Network.from("mainnet"); + } + // Canonical name or chain ID + if (typeof (network) === "number") { + network = BigInt(network); + } + if (typeof (network) === "string" || typeof (network) === "bigint") { + const networkFunc = Networks.get(network); + if (networkFunc) { + return networkFunc(); + } + if (typeof (network) === "bigint") { + return new Network("unknown", network); + } + (0,errors/* assertArgument */.MR)(false, "unknown network", "network", network); + } + // Clonable with network-like abilities + if (typeof (network.clone) === "function") { + const clone = network.clone(); + //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") { + //} + return clone; + } + // Networkish + if (typeof (network) === "object") { + (0,errors/* assertArgument */.MR)(typeof (network.name) === "string" && typeof (network.chainId) === "number", "invalid network object name or chainId", "network", network); + const custom = new Network((network.name), (network.chainId)); + if (network.ensAddress || network.ensNetwork != null) { + custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork)); + } + //if ((network).layerOneConnection) { + // custom.attachPlugin(new LayerOneConnectionPlugin((network).layerOneConnection)); + //} + return custom; + } + (0,errors/* assertArgument */.MR)(false, "invalid network", "network", network); + } + /** + * Register %%nameOrChainId%% with a function which returns + * an instance of a Network representing that chain. + */ + static register(nameOrChainId, networkFunc) { + if (typeof (nameOrChainId) === "number") { + nameOrChainId = BigInt(nameOrChainId); + } + const existing = Networks.get(nameOrChainId); + if (existing) { + (0,errors/* assertArgument */.MR)(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } +} +// We don't want to bring in formatUnits because it is backed by +// FixedNumber and we want to keep Networks tiny. The values +// included by the Gas Stations are also IEEE 754 with lots of +// rounding issues and exceed the strict checks formatUnits has. +function parseUnits(_value, decimals) { + const value = String(_value); + if (!value.match(/^[0-9.]+$/)) { + throw new Error(`invalid gwei value: ${_value}`); + } + // Break into [ whole, fraction ] + const comps = value.split("."); + if (comps.length === 1) { + comps.push(""); + } + // More than 1 decimal point or too many fractional positions + if (comps.length !== 2) { + throw new Error(`invalid gwei value: ${_value}`); + } + // Pad the fraction to 9 decimalplaces + while (comps[1].length < decimals) { + comps[1] += "0"; + } + // Too many decimals and some non-zero ending, take the ceiling + if (comps[1].length > 9) { + let frac = BigInt(comps[1].substring(0, 9)); + if (!comps[1].substring(9).match(/^0+$/)) { + frac++; + } + comps[1] = frac.toString(); + } + return BigInt(comps[0] + comps[1]); +} +// Used by Polygon to use a gas station for fee data +function getGasStationPlugin(url) { + return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => { + // Prevent Cloudflare from blocking our request in node.js + request.setHeader("User-Agent", "ethers"); + let response; + try { + const [_response, _feeData] = await Promise.all([ + request.send(), fetchFeeData() + ]); + response = _response; + const payload = response.bodyJson.standard; + const feeData = { + gasPrice: _feeData.gasPrice, + maxFeePerGas: parseUnits(payload.maxFee, 9), + maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9), + }; + return feeData; + } + catch (error) { + (0,errors/* assert */.vA)(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { request, response, error }); + } + }); +} +// See: https://chainlist.org +let injected = false; +function injectCommonNetworks() { + if (injected) { + return; + } + injected = true; + /// Register popular Ethereum networks + function registerEth(name, chainId, options) { + const func = function () { + const network = new Network(name, chainId); + // We use 0 to disable ENS + if (options.ensNetwork != null) { + network.attachPlugin(new EnsPlugin(null, options.ensNetwork)); + } + network.attachPlugin(new GasCostPlugin()); + (options.plugins || []).forEach((plugin) => { + network.attachPlugin(plugin); + }); + return network; + }; + // Register the network by name and chain ID + Network.register(name, func); + Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name) => { + Network.register(name, func); + }); + } + } + registerEth("mainnet", 1, { ensNetwork: 1, altNames: ["homestead"] }); + registerEth("ropsten", 3, { ensNetwork: 3 }); + registerEth("rinkeby", 4, { ensNetwork: 4 }); + registerEth("goerli", 5, { ensNetwork: 5 }); + registerEth("kovan", 42, { ensNetwork: 42 }); + registerEth("sepolia", 11155111, { ensNetwork: 11155111 }); + registerEth("holesky", 17000, { ensNetwork: 17000 }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("arbitrum", 42161, { + ensNetwork: 1, + }); + registerEth("arbitrum-goerli", 421613, {}); + registerEth("arbitrum-sepolia", 421614, {}); + registerEth("base", 8453, { ensNetwork: 1 }); + registerEth("base-goerli", 84531, {}); + registerEth("base-sepolia", 84532, {}); + registerEth("bnb", 56, { ensNetwork: 1 }); + registerEth("bnbt", 97, {}); + registerEth("linea", 59144, { ensNetwork: 1 }); + registerEth("linea-goerli", 59140, {}); + registerEth("linea-sepolia", 59141, {}); + registerEth("matic", 137, { + ensNetwork: 1, + plugins: [ + getGasStationPlugin("https:/\/gasstation.polygon.technology/v2") + ] + }); + registerEth("matic-amoy", 80002, {}); + registerEth("matic-mumbai", 80001, { + altNames: ["maticMumbai", "maticmum"], + plugins: [ + getGasStationPlugin("https:/\/gasstation-testnet.polygon.technology/v2") + ] + }); + registerEth("optimism", 10, { + ensNetwork: 1, + plugins: [] + }); + registerEth("optimism-goerli", 420, {}); + registerEth("optimism-sepolia", 11155420, {}); + registerEth("xdai", 100, { ensNetwork: 1 }); +} +//# sourceMappingURL=network.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/providers/provider.js +var providers_provider = __webpack_require__(43948); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/subscriber-polling.js +/* provided dependency */ var console = __webpack_require__(96763); + +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +/** + * Return the polling subscriber for common events. + * + * @_docloc: api/providers/abstract-provider + */ +function getPollingSubscriber(provider, event) { + if (event === "block") { + return new PollingBlockSubscriber(provider); + } + if (isHexString(event, 32)) { + return new PollingTransactionSubscriber(provider, event); + } + assert(false, "unsupported polling event", "UNSUPPORTED_OPERATION", { + operation: "getPollingSubscriber", info: { event } + }); +} +// @TODO: refactor this +/** + * A **PollingBlockSubscriber** polls at a regular interval for a change + * in the block number. + * + * @_docloc: api/providers/abstract-provider + */ +class PollingBlockSubscriber { + #provider; + #poller; + #interval; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + /** + * Create a new **PollingBlockSubscriber** attached to %%provider%%. + */ + constructor(provider) { + this.#provider = provider; + this.#poller = null; + this.#interval = 4000; + this.#blockNumber = -2; + } + /** + * The polling interval. + */ + get pollingInterval() { return this.#interval; } + set pollingInterval(value) { this.#interval = value; } + async #poll() { + try { + const blockNumber = await this.#provider.getBlockNumber(); + // Bootstrap poll to setup our initial block number + if (this.#blockNumber === -2) { + this.#blockNumber = blockNumber; + return; + } + // @TODO: Put a cap on the maximum number of events per loop? + if (blockNumber !== this.#blockNumber) { + for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { + // We have been stopped + if (this.#poller == null) { + return; + } + await this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + } + } + catch (error) { + // @TODO: Minor bump, add an "error" event to let subscribers + // know things went awry. + //console.log(error); + } + // We have been stopped + if (this.#poller == null) { + return; + } + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + start() { + if (this.#poller) { + return; + } + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + this.#poll(); + } + stop() { + if (!this.#poller) { + return; + } + this.#provider._clearTimeout(this.#poller); + this.#poller = null; + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +/** + * An **OnBlockSubscriber** can be sub-classed, with a [[_poll]] + * implmentation which will be called on every new block. + * + * @_docloc: api/providers/abstract-provider + */ +class OnBlockSubscriber { + #provider; + #poll; + #running; + /** + * Create a new **OnBlockSubscriber** attached to %%provider%%. + */ + constructor(provider) { + this.#provider = provider; + this.#running = false; + this.#poll = (blockNumber) => { + this._poll(blockNumber, this.#provider); + }; + } + /** + * Called on every new block. + */ + async _poll(blockNumber, provider) { + throw new Error("sub-classes must override this"); + } + start() { + if (this.#running) { + return; + } + this.#running = true; + this.#poll(-2); + this.#provider.on("block", this.#poll); + } + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#provider.off("block", this.#poll); + } + pause(dropWhilePaused) { this.stop(); } + resume() { this.start(); } +} +class PollingBlockTagSubscriber extends OnBlockSubscriber { + #tag; + #lastBlock; + constructor(provider, tag) { + super(provider); + this.#tag = tag; + this.#lastBlock = -2; + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#lastBlock = -2; + } + super.pause(dropWhilePaused); + } + async _poll(blockNumber, provider) { + const block = await provider.getBlock(this.#tag); + if (block == null) { + return; + } + if (this.#lastBlock === -2) { + this.#lastBlock = block.number; + } + else if (block.number > this.#lastBlock) { + provider.emit(this.#tag, block.number); + this.#lastBlock = block.number; + } + } +} +/** + * @_ignore: + * + * @_docloc: api/providers/abstract-provider + */ +class PollingOrphanSubscriber extends OnBlockSubscriber { + #filter; + constructor(provider, filter) { + super(provider); + this.#filter = copy(filter); + } + async _poll(blockNumber, provider) { + throw new Error("@TODO"); + console.log(this.#filter); + } +} +/** + * A **PollingTransactionSubscriber** will poll for a given transaction + * hash for its receipt. + * + * @_docloc: api/providers/abstract-provider + */ +class PollingTransactionSubscriber extends OnBlockSubscriber { + #hash; + /** + * Create a new **PollingTransactionSubscriber** attached to + * %%provider%%, listening for %%hash%%. + */ + constructor(provider, hash) { + super(provider); + this.#hash = hash; + } + async _poll(blockNumber, provider) { + const tx = await provider.getTransactionReceipt(this.#hash); + if (tx) { + provider.emit(this.#hash, tx); + } + } +} +/** + * A **PollingEventSubscriber** will poll for a given filter for its logs. + * + * @_docloc: api/providers/abstract-provider + */ +class PollingEventSubscriber { + #provider; + #filter; + #poller; + #running; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + /** + * Create a new **PollingTransactionSubscriber** attached to + * %%provider%%, listening for %%filter%%. + */ + constructor(provider, filter) { + this.#provider = provider; + this.#filter = copy(filter); + this.#poller = this.#poll.bind(this); + this.#running = false; + this.#blockNumber = -2; + } + async #poll(blockNumber) { + // The initial block hasn't been determined yet + if (this.#blockNumber === -2) { + return; + } + const filter = copy(this.#filter); + filter.fromBlock = this.#blockNumber + 1; + filter.toBlock = blockNumber; + const logs = await this.#provider.getLogs(filter); + // No logs could just mean the node has not indexed them yet, + // so we keep a sliding window of 60 blocks to keep scanning + if (logs.length === 0) { + if (this.#blockNumber < blockNumber - 60) { + this.#blockNumber = blockNumber - 60; + } + return; + } + for (const log of logs) { + this.#provider.emit(this.#filter, log); + // Only advance the block number when logs were found to + // account for networks (like BNB and Polygon) which may + // sacrifice event consistency for block event speed + this.#blockNumber = log.blockNumber; + } + } + start() { + if (this.#running) { + return; + } + this.#running = true; + if (this.#blockNumber === -2) { + this.#provider.getBlockNumber().then((blockNumber) => { + this.#blockNumber = blockNumber; + }); + } + this.#provider.on("block", this.#poller); + } + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +//# sourceMappingURL=subscriber-polling.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/abstract-provider.js +/* provided dependency */ var abstract_provider_console = __webpack_require__(96763); +/** + * The available providers should suffice for most developers purposes, + * but the [[AbstractProvider]] class has many features which enable + * sub-classing it for specific purposes. + * + * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider] + */ +// @TODO +// Event coalescence +// When we register an event with an async value (e.g. address is a Signer +// or ENS name), we need to add it immeidately for the Event API, but also +// need time to resolve the address. Upon resolving the address, we need to +// migrate the listener to the static event. We also need to maintain a map +// of Signer/ENS name to address so we can sync respond to listenerCount. + + + + + + + + + + + +// Constants +const BN_2 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function isPromise(value) { + return (value && typeof (value.then) === "function"); +} +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + if (v == null) { + return "null"; + } + if (typeof (v) === "bigint") { + return `bigint:${v.toString()}`; + } + if (typeof (v) === "string") { + return v.toLowerCase(); + } + // Sort object keys + if (typeof (v) === "object" && !Array.isArray(v)) { + const keys = Object.keys(v); + keys.sort(); + return keys.reduce((accum, key) => { + accum[key] = v[key]; + return accum; + }, {}); + } + return v; + }); +} +/** + * An **UnmanagedSubscriber** is useful for events which do not require + * any additional management, such as ``"debug"`` which only requires + * emit in synchronous event loop triggered calls. + */ +class UnmanagedSubscriber { + /** + * The name fof the event. + */ + name; + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name) { (0,properties/* defineProperties */.n)(this, { name }); } + start() { } + stop() { } + pause(dropWhilePaused) { } + resume() { } +} +function abstract_provider_copy(value) { + return JSON.parse(JSON.stringify(value)); +} +function concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +async function getSubscription(_event, provider) { + if (_event == null) { + throw new Error("invalid event"); + } + // Normalize topic array info an EventFilter + if (Array.isArray(_event)) { + _event = { topics: _event }; + } + if (typeof (_event) === "string") { + switch (_event) { + case "block": + case "debug": + case "error": + case "finalized": + case "network": + case "pending": + case "safe": { + return { type: _event, tag: _event }; + } + } + } + if ((0,utils_data/* isHexString */.Lo)(_event, 32)) { + const hash = _event.toLowerCase(); + return { type: "transaction", tag: getTag("tx", { hash }), hash }; + } + if (_event.orphan) { + const event = _event; + // @TODO: Should lowercase and whatnot things here instead of copy... + return { type: "orphan", tag: getTag("orphan", event), filter: abstract_provider_copy(event) }; + } + if ((_event.address || _event.topics)) { + const event = _event; + const filter = { + topics: ((event.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + })) + }; + if (event.address) { + const addresses = []; + const promises = []; + const addAddress = (addr) => { + if ((0,utils_data/* isHexString */.Lo)(addr)) { + addresses.push(addr); + } + else { + promises.push((async () => { + addresses.push(await (0,checks/* resolveAddress */.tG)(addr, provider)); + })()); + } + }; + if (Array.isArray(event.address)) { + event.address.forEach(addAddress); + } + else { + addAddress(event.address); + } + if (promises.length) { + await Promise.all(promises); + } + filter.address = concisify(addresses.map((a) => a.toLowerCase())); + } + return { filter, tag: getTag("event", filter), type: "event" }; + } + (0,errors/* assertArgument */.MR)(false, "unknown ProviderEvent", "event", _event); +} +function abstract_provider_getTime() { return (new Date()).getTime(); } +const defaultOptions = { + cacheTimeout: 250, + pollingInterval: 4000 +}; +/** + * An **AbstractProvider** provides a base class for other sub-classes to + * implement the [[Provider]] API by normalizing input arguments and + * formatting output results as well as tracking events for consistent + * behaviour on an eventually-consistent network. + */ +class AbstractProvider { + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #destroyed; + #networkPromise; + #anyNetwork; + #performCache; + // The most recent block number if running an event or -1 if no "block" event + #lastBlockNumber; + #nextTimer; + #timers; + #disableCcipRead; + #options; + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network, options) { + this.#options = Object.assign({}, defaultOptions, options || {}); + if (_network === "any") { + this.#anyNetwork = true; + this.#networkPromise = null; + } + else if (_network) { + const network = Network.from(_network); + this.#anyNetwork = false; + this.#networkPromise = Promise.resolve(network); + setTimeout(() => { this.emit("network", network, null); }, 0); + } + else { + this.#anyNetwork = false; + this.#networkPromise = null; + } + this.#lastBlockNumber = -1; + this.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#destroyed = false; + this.#nextTimer = 1; + this.#timers = new Map(); + this.#disableCcipRead = false; + } + get pollingInterval() { return this.#options.pollingInterval; } + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider() { return this; } + /** + * Returns all the registered plug-ins. + */ + get plugins() { + return Array.from(this.#plugins.values()); + } + /** + * Attach a new plug-in. + */ + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.connect(this)); + return this; + } + /** + * Get a plugin by name. + */ + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead() { return this.#disableCcipRead; } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + // Shares multiple identical requests made during the same 250ms + async #perform(req) { + const timeout = this.#options.cacheTimeout; + // Caching disabled + if (timeout < 0) { + return await this._perform(req); + } + // Create a tag + const tag = getTag(req.method, req); + let perform = this.#performCache.get(tag); + if (!perform) { + perform = this._perform(req); + this.#performCache.set(tag, perform); + setTimeout(() => { + if (this.#performCache.get(tag) === perform) { + this.#performCache.delete(tag); + } + }, timeout); + } + return await perform; + } + /** + * Resolves to the data for executing the CCIP-read operations. + */ + async ccipReadFetch(tx, calldata, urls) { + if (this.disableCcipRead || urls.length === 0 || tx.to == null) { + return null; + } + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + // URL expansion + const href = url.replace("{sender}", sender).replace("{data}", data); + // If no {data} is present, use POST; otherwise GET + //const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender }); + //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => { + // value.status = response.statusCode; + // return value; + //}); + const request = new FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { data, sender }; + } + this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls }); + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + this.emit("debug", { action: "receiveCcipReadFetchResult", request, result }); + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + this.emit("debug", { action: "receiveCcipReadFetchError", request, result }); + } + catch (error) { } + // 4xx indicates the result is not present; stop + (0,errors/* assert */.vA)(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } }); + // 5xx indicates server issue; try the next url + errorMessages.push(errorMessage); + } + (0,errors/* assert */.vA)(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value, network) { + return new providers_provider/* Block */.eB(formatBlock(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value, network) { + return new providers_provider/* Log */.tG(formatLog(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value, network) { + return new providers_provider/* TransactionReceipt */.z5(formatTransactionReceipt(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx, network) { + return new providers_provider/* TransactionResponse */.uI(formatTransactionResponse(tx), this); + } + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork() { + (0,errors/* assert */.vA)(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + async _perform(req) { + (0,errors/* assert */.vA)(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber() { + const blockNumber = (0,maths/* getNumber */.WZ)(await this.#perform({ method: "getBlockNumber" }), "%response"); + if (this.#lastBlockNumber >= 0) { + this.#lastBlockNumber = blockNumber; + } + return blockNumber; + } + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address) { + return (0,checks/* resolveAddress */.tG)(address, this); + } + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "finalized": + case "latest": + case "pending": + case "safe": + return blockTag; + } + if ((0,utils_data/* isHexString */.Lo)(blockTag)) { + if ((0,utils_data/* isHexString */.Lo)(blockTag, 32)) { + return blockTag; + } + return (0,maths/* toQuantity */.nD)(blockTag); + } + if (typeof (blockTag) === "bigint") { + blockTag = (0,maths/* getNumber */.WZ)(blockTag, "blockTag"); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return (0,maths/* toQuantity */.nD)(blockTag); + } + if (this.#lastBlockNumber >= 0) { + return (0,maths/* toQuantity */.nD)(this.#lastBlockNumber + blockTag); + } + return this.getBlockNumber().then((b) => (0,maths/* toQuantity */.nD)(b + blockTag)); + } + (0,errors/* assertArgument */.MR)(false, "invalid blockTag", "blockTag", blockTag); + } + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter) { + // Create a canonical representation of the topics + const topics = (filter.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + }); + const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined; + const resolve = (_address, fromBlock, toBlock) => { + let address = undefined; + switch (_address.length) { + case 0: break; + case 1: + address = _address[0]; + break; + default: + _address.sort(); + address = _address; + } + if (blockHash) { + if (fromBlock != null || toBlock != null) { + throw new Error("invalid filter"); + } + } + const filter = {}; + if (address) { + filter.address = address; + } + if (topics.length) { + filter.topics = topics; + } + if (fromBlock) { + filter.fromBlock = fromBlock; + } + if (toBlock) { + filter.toBlock = toBlock; + } + if (blockHash) { + filter.blockHash = blockHash; + } + return filter; + }; + // Addresses could be async (ENS names or Addressables) + let address = []; + if (filter.address) { + if (Array.isArray(filter.address)) { + for (const addr of filter.address) { + address.push(this._getAddress(addr)); + } + } + else { + address.push(this._getAddress(filter.address)); + } + } + let fromBlock = undefined; + if ("fromBlock" in filter) { + fromBlock = this._getBlockTag(filter.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.toBlock); + } + if (address.filter((a) => (typeof (a) !== "string")).length || + (fromBlock != null && typeof (fromBlock) !== "string") || + (toBlock != null && typeof (toBlock) !== "string")) { + return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => { + return resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); + } + /** + * Returns or resovles to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request) { + const request = (0,providers_provider/* copyRequest */.VS)(_request); + const promises = []; + ["to", "from"].forEach((key) => { + if (request[key] == null) { + return; + } + const addr = (0,checks/* resolveAddress */.tG)(request[key], this); + if (isPromise(addr)) { + promises.push((async function () { request[key] = await addr; })()); + } + else { + request[key] = addr; + } + }); + if (request.blockTag != null) { + const blockTag = this._getBlockTag(request.blockTag); + if (isPromise(blockTag)) { + promises.push((async function () { request.blockTag = await blockTag; })()); + } + else { + request.blockTag = blockTag; + } + } + if (promises.length) { + return (async function () { + await Promise.all(promises); + return request; + })(); + } + return request; + } + async getNetwork() { + // No explicit network was set and this is our first time + if (this.#networkPromise == null) { + // Detect the current network (shared with all calls) + const detectNetwork = (async () => { + try { + const network = await this._detectNetwork(); + this.emit("network", network, null); + return network; + } + catch (error) { + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + } + })(); + this.#networkPromise = detectNetwork; + return (await detectNetwork).clone(); + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() // The actual connected network + ]); + if (expected.chainId !== actual.chainId) { + if (this.#anyNetwork) { + // The "any" network can change, so notify listeners + this.emit("network", actual, expected); + // Update the network if something else hasn't already changed it + if (this.#networkPromise === networkPromise) { + this.#networkPromise = Promise.resolve(actual); + } + } + else { + // Otherwise, we do not allow changes to the underlying network + (0,errors/* assert */.vA)(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone(); + } + async getFeeData() { + const network = await this.getNetwork(); + const getFeeDataFunc = async () => { + const { _block, gasPrice, priorityFee } = await (0,properties/* resolveProperties */.k)({ + _block: this.#getBlock("latest", false), + gasPrice: ((async () => { + try { + const value = await this.#perform({ method: "getGasPrice" }); + return (0,maths/* getBigInt */.Ab)(value, "%response"); + } + catch (error) { } + return null; + })()), + priorityFee: ((async () => { + try { + const value = await this.#perform({ method: "getPriorityFee" }); + return (0,maths/* getBigInt */.Ab)(value, "%response"); + } + catch (error) { } + return null; + })()) + }); + let maxFeePerGas = null; + let maxPriorityFeePerGas = null; + // These are the recommended EIP-1559 heuristics for fee data + const block = this._wrapBlock(_block, network); + if (block && block.baseFeePerGas) { + maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt("1000000000"); + maxFeePerGas = (block.baseFeePerGas * BN_2) + maxPriorityFeePerGas; + } + return new providers_provider/* FeeData */.J9(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + }; + // Check for a FeeDataNetWorkPlugin + const plugin = network.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + if (plugin) { + const req = new FetchRequest(plugin.url); + const feeData = await plugin.processFunc(getFeeDataFunc, this, req); + return new providers_provider/* FeeData */.J9(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); + } + return await getFeeDataFunc(); + } + async estimateGas(_tx) { + let tx = this._getTransactionRequest(_tx); + if (isPromise(tx)) { + tx = await tx; + } + return (0,maths/* getBigInt */.Ab)(await this.#perform({ + method: "estimateGas", transaction: tx + }), "%response"); + } + async #call(tx, blockTag, attempt) { + (0,errors/* assert */.vA)(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + // This came in as a PerformActionTransaction, so to/from are safe; we can cast + const transaction = (0,providers_provider/* copyRequest */.VS)(tx); + try { + return (0,utils_data/* hexlify */.c$)(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + if (!this.disableCcipRead && (0,errors/* isCallException */.E)(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && (0,utils_data/* dataSlice */.ZG)(error.data, 0, 4) === "0x556f1830") { + const data = error.data; + const txSender = await (0,checks/* resolveAddress */.tG)(transaction.to, this); + // Parse the CCIP Read Arguments + let ccipArgs; + try { + ccipArgs = parseOffchainLookup((0,utils_data/* dataSlice */.ZG)(error.data, 4)); + } + catch (error) { + (0,errors/* assert */.vA)(false, error.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", transaction, info: { data } + }); + } + // Check the sender of the OffchainLookup matches the transaction + (0,errors/* assert */.vA)(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", { + action: "call", + data, + reason: "OffchainLookup", + transaction: transaction, + invocation: null, + revert: { + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + name: "OffchainLookup", + args: ccipArgs.errorArgs + } + }); + const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + (0,errors/* assert */.vA)(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } + }); + const tx = { + to: txSender, + data: (0,utils_data/* concat */.xW)([ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData])]) + }; + this.emit("debug", { action: "sendCcipReadCall", transaction: tx }); + try { + const result = await this.#call(tx, blockTag, attempt + 1); + this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx), result }); + return result; + } + catch (error) { + this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({}, tx), error }); + throw error; + } + } + throw error; + } + } + async #checkNetwork(promise) { + const { value } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + value: promise + }); + return value; + } + async call(_tx) { + const { tx, blockTag } = await (0,properties/* resolveProperties */.k)({ + tx: this._getTransactionRequest(_tx), + blockTag: this._getBlockTag(_tx.blockTag) + }); + return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1)); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag }))); + } + async getBalance(address, blockTag) { + return (0,maths/* getBigInt */.Ab)(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return (0,maths/* getNumber */.WZ)(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return (0,utils_data/* hexlify */.c$)(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorage(address, _position, blockTag) { + const position = (0,maths/* getBigInt */.Ab)(_position, "position"); + return (0,utils_data/* hexlify */.c$)(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag)); + } + // Write + async broadcastTransaction(signedTx) { + const { blockNumber, hash, network } = await (0,properties/* resolveProperties */.k)({ + blockNumber: this.getBlockNumber(), + hash: this._perform({ + method: "broadcastTransaction", + signedTransaction: signedTx + }), + network: this.getNetwork() + }); + const tx = transaction/* Transaction */.Z.from(signedTx); + if (tx.hash !== hash) { + throw new Error("@TODO: the returned hash did not match"); + } + return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); + } + async #getBlock(block, includeTransactions) { + // @TODO: Add CustomBlockPlugin check + if ((0,utils_data/* isHexString */.Lo)(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions + }); + } + let blockTag = this._getBlockTag(block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions + }); + } + // Queries + async getBlock(block, prefetchTxs) { + const { network, params } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + params: this.#getBlock(block, !!prefetchTxs) + }); + if (params == null) { + return null; + } + return this._wrapBlock(params, network); + } + async getTransaction(hash) { + const { network, params } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransaction", hash }) + }); + if (params == null) { + return null; + } + return this._wrapTransactionResponse(params, network); + } + async getTransactionReceipt(hash) { + const { network, params } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransactionReceipt", hash }) + }); + if (params == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice into old transactions + // in the receipt, so we look it up manually and inject it. + if (params.gasPrice == null && params.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash }); + if (tx == null) { + throw new Error("report this; could not find tx or effectiveGasPrice"); + } + params.effectiveGasPrice = tx.gasPrice; + } + return this._wrapTransactionReceipt(params, network); + } + async getTransactionResult(hash) { + const { result } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + result: this.#perform({ method: "getTransactionResult", hash }) + }); + if (result == null) { + return null; + } + return (0,utils_data/* hexlify */.c$)(result); + } + // Bloom-filter Queries + async getLogs(_filter) { + let filter = this._getFilter(_filter); + if (isPromise(filter)) { + filter = await filter; + } + const { network, params } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + params: this.#perform({ method: "getLogs", filter }) + }); + return params.map((p) => this._wrapLog(p, network)); + } + // ENS + _getProvider(chainId) { + (0,errors/* assert */.vA)(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { + operation: "_getProvider()" + }); + } + async getResolver(name) { + return await EnsResolver.fromName(this, name); + } + async getAvatar(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAvatar(); + } + return null; + } + async resolveName(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + return null; + } + async lookupAddress(address) { + address = (0,address_address/* getAddress */.b)(address); + const node = (0,namehash/* namehash */.kM)(address.substring(2).toLowerCase() + ".addr.reverse"); + try { + const ensAddr = await EnsResolver.getEnsAddress(this); + const ensContract = new contract_contract/* Contract */.NZ(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], this); + const resolver = await ensContract.resolver(node); + if (resolver == null || resolver === addresses/* ZeroAddress */.j) { + return null; + } + const resolverContract = new contract_contract/* Contract */.NZ(resolver, [ + "function name(bytes32) view returns (string)" + ], this); + const name = await resolverContract.name(node); + // Failed forward resolution + const check = await this.resolveName(name); + if (check !== address) { + return null; + } + return name; + } + catch (error) { + // No data was returned from the resolver + if ((0,errors/* isError */.bJ)(error, "BAD_DATA") && error.value === "0x") { + return null; + } + // Something reerted + if ((0,errors/* isError */.bJ)(error, "CALL_EXCEPTION")) { + return null; + } + throw error; + } + return null; + } + async waitForTransaction(hash, _confirms, timeout) { + const confirms = (_confirms != null) ? _confirms : 1; + if (confirms === 0) { + return this.getTransactionReceipt(hash); + } + return new Promise(async (resolve, reject) => { + let timer = null; + const listener = (async (blockNumber) => { + try { + const receipt = await this.getTransactionReceipt(hash); + if (receipt != null) { + if (blockNumber - receipt.blockNumber + 1 >= confirms) { + resolve(receipt); + //this.off("block", listener); + if (timer) { + clearTimeout(timer); + timer = null; + } + return; + } + } + } + catch (error) { + abstract_provider_console.log("EEE", error); + } + this.once("block", listener); + }); + if (timeout != null) { + timer = setTimeout(() => { + if (timer == null) { + return; + } + timer = null; + this.off("block", listener); + reject((0,errors/* makeError */.xz)("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber()); + }); + } + async waitForBlock(blockTag) { + (0,errors/* assert */.vA)(false, "not implemented yet", "NOT_IMPLEMENTED", { + operation: "waitForBlock" + }); + } + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func, timeout) { + if (timeout == null) { + timeout = 0; + } + const timerId = this.#nextTimer++; + const func = () => { + this.#timers.delete(timerId); + _func(); + }; + if (this.paused) { + this.#timers.set(timerId, { timer: null, func, time: timeout }); + } + else { + const timer = setTimeout(func, timeout); + this.#timers.set(timerId, { timer, func, time: abstract_provider_getTime() }); + } + return timerId; + } + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "error": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": { + const subscriber = new PollingBlockSubscriber(this); + subscriber.pollingInterval = this.pollingInterval; + return subscriber; + } + case "safe": + case "finalized": + return new PollingBlockTagSubscriber(this, sub.type); + case "event": + return new PollingEventSubscriber(this, sub.filter); + case "transaction": + return new PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new PollingOrphanSubscriber(this, sub.filter); + } + throw new Error(`unsupported event: ${sub.type}`); + } + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub, newSub) { + for (const sub of this.#subs.values()) { + if (sub.subscriber === oldSub) { + if (sub.started) { + sub.subscriber.stop(); + } + sub.subscriber = newSub; + if (sub.started) { + newSub.start(); + } + if (this.#pausedState != null) { + newSub.pause(this.#pausedState); + } + break; + } + } + } + async #hasSub(event, emitArgs) { + let sub = await getSubscription(event, this); + // This is a log that is removing an existing log; we actually want + // to emit an orphan event for the removed log + if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { + sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this); + } + return this.#subs.get(sub.tag) || null; + } + async #getSub(event) { + const subscription = await getSubscription(event, this); + // Prevent tampering with our tag in any subclass' _getSubscriber + const tag = subscription.tag; + let sub = this.#subs.get(tag); + if (!sub) { + const subscriber = this._getSubscriber(subscription); + const addressableMap = new WeakMap(); + const nameMap = new Map(); + sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] }; + this.#subs.set(tag, sub); + } + return sub; + } + async on(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: false }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async once(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: true }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async emit(event, ...args) { + const sub = await this.#hasSub(event, args); + // If there is not subscription or if a recent emit removed + // the last of them (which also deleted the sub) do nothing + if (!sub || sub.listeners.length === 0) { + return false; + } + ; + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const payload = new events/* EventPayload */.z(this, (once ? null : listener), event); + try { + listener.call(this, ...args, payload); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return (count > 0); + } + async listenerCount(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + let total = 0; + for (const { listeners } of this.#subs.values()) { + total += listeners.length; + } + return total; + } + async listeners(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + let result = []; + for (const { listeners } of this.#subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + async off(event, listener) { + const sub = await this.#hasSub(event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (!listener || sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return this; + } + async removeAllListeners(event) { + if (event) { + const { tag, started, subscriber } = await this.#getSub(event); + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + else { + for (const [tag, { started, subscriber }] of this.#subs) { + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + } + return this; + } + // Alias for "on" + async addListener(event, listener) { + return await this.on(event, listener); + } + // Alias for "off" + async removeListener(event, listener) { + return this.off(event, listener); + } + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed() { + return this.#destroyed; + } + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + this.#destroyed = true; + } + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused) { + this.#lastBlockNumber = -1; + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + (0,errors/* assert */.vA)(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { + operation: "pause" + }); + } + this._forEachSubscriber((s) => s.pause(dropWhilePaused)); + this.#pausedState = !!dropWhilePaused; + for (const timer of this.#timers.values()) { + // Clear the timer + if (timer.timer) { + clearTimeout(timer.timer); + } + // Remaining time needed for when we become unpaused + timer.time = abstract_provider_getTime() - timer.time; + } + } + /** + * Resume the provider. + */ + resume() { + if (this.#pausedState == null) { + return; + } + this._forEachSubscriber((s) => s.resume()); + this.#pausedState = null; + for (const timer of this.#timers.values()) { + // Remaining time when we were paused + let timeout = timer.time; + if (timeout < 0) { + timeout = 0; + } + // Start time (in cause paused, so we con compute remaininf time) + timer.time = abstract_provider_getTime(); + // Start the timer + setTimeout(timer.func, timeout); + } + } +} +function _parseString(result, start) { + try { + const bytes = _parseBytes(result, start); + if (bytes) { + return (0,utf8/* toUtf8String */._v)(bytes); + } + } + catch (error) { } + return null; +} +function _parseBytes(result, start) { + if (result === "0x") { + return null; + } + try { + const offset = (0,maths/* getNumber */.WZ)((0,utils_data/* dataSlice */.ZG)(result, start, start + 32)); + const length = (0,maths/* getNumber */.WZ)((0,utils_data/* dataSlice */.ZG)(result, offset, offset + 32)); + return (0,utils_data/* dataSlice */.ZG)(result, offset + 32, offset + 32 + length); + } + catch (error) { } + return null; +} +function numPad(value) { + const result = (0,maths/* toBeArray */.c4)(value); + if (result.length > 32) { + throw new Error("internal; should not happen"); + } + const padded = new Uint8Array(32); + padded.set(result, 32 - result.length); + return padded; +} +function bytesPad(value) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +const empty = new Uint8Array([]); +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + let byteCount = 0; + // Add place-holders for pointers as we add items + for (let i = 0; i < datas.length; i++) { + result.push(empty); + byteCount += 32; + } + for (let i = 0; i < datas.length; i++) { + const data = (0,utils_data/* getBytes */.q5)(datas[i]); + // Update the bytes offset + result[i] = numPad(byteCount); + // The length and padded value of data + result.push(numPad(data.length)); + result.push(bytesPad(data)); + byteCount += 32 + Math.ceil(data.length / 32) * 32; + } + return (0,utils_data/* concat */.xW)(result); +} +const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000"; +function parseOffchainLookup(data) { + const result = { + sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: [] + }; + (0,errors/* assert */.vA)((0,utils_data/* dataLength */.pO)(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { + reason: "insufficient OffchainLookup data" + }); + const sender = (0,utils_data/* dataSlice */.ZG)(data, 0, 32); + (0,errors/* assert */.vA)((0,utils_data/* dataSlice */.ZG)(sender, 0, 12) === (0,utils_data/* dataSlice */.ZG)(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup sender" + }); + result.sender = (0,utils_data/* dataSlice */.ZG)(sender, 12); + // Read the URLs from the response + try { + const urls = []; + const urlsOffset = (0,maths/* getNumber */.WZ)((0,utils_data/* dataSlice */.ZG)(data, 32, 64)); + const urlsLength = (0,maths/* getNumber */.WZ)((0,utils_data/* dataSlice */.ZG)(data, urlsOffset, urlsOffset + 32)); + const urlsData = (0,utils_data/* dataSlice */.ZG)(data, urlsOffset + 32); + for (let u = 0; u < urlsLength; u++) { + const url = _parseString(urlsData, u * 32); + if (url == null) { + throw new Error("abort"); + } + urls.push(url); + } + result.urls = urls; + } + catch (error) { + (0,errors/* assert */.vA)(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup urls" + }); + } + // Get the CCIP calldata to forward + try { + const calldata = _parseBytes(data, 64); + if (calldata == null) { + throw new Error("abort"); + } + result.calldata = calldata; + } + catch (error) { + (0,errors/* assert */.vA)(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup calldata" + }); + } + // Get the callbackSelector (bytes4) + (0,errors/* assert */.vA)((0,utils_data/* dataSlice */.ZG)(data, 100, 128) === (0,utils_data/* dataSlice */.ZG)(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup callbaackSelector" + }); + result.selector = (0,utils_data/* dataSlice */.ZG)(data, 96, 100); + // Get the extra data to send back to the contract as context + try { + const extraData = _parseBytes(data, 128); + if (extraData == null) { + throw new Error("abort"); + } + result.extraData = extraData; + } + catch (error) { + (0,errors/* assert */.vA)(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup extraData" + }); + } + result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => result[k]); + return result; +} +//# sourceMappingURL=abstract-provider.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/abstract-signer.js +/** + * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes + * are sufficent for most developers, but this is provided to + * fascilitate more complex Signers. + * + * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] + */ + + + + +function checkProvider(signer, operation) { + if (signer.provider) { + return signer.provider; + } + (0,errors/* assert */.vA)(false, "missing provider", "UNSUPPORTED_OPERATION", { operation }); +} +async function populate(signer, tx) { + let pop = (0,providers_provider/* copyRequest */.VS)(tx); + if (pop.to != null) { + pop.to = (0,checks/* resolveAddress */.tG)(pop.to, signer); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + signer.getAddress(), + (0,checks/* resolveAddress */.tG)(from, signer) + ]).then(([address, from]) => { + (0,errors/* assertArgument */.MR)(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from); + return address; + }); + } + else { + pop.from = signer.getAddress(); + } + return await (0,properties/* resolveProperties */.k)(pop); +} +/** + * An **AbstractSigner** includes most of teh functionality required + * to get a [[Signer]] working as expected, but requires a few + * Signer-specific methods be overridden. + * + */ +class AbstractSigner { + /** + * The provider this signer is connected to. + */ + provider; + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider) { + (0,properties/* defineProperties */.n)(this, { provider: (provider || null) }); + } + async getNonce(blockTag) { + return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async populateCall(tx) { + const pop = await populate(this, tx); + return pop; + } + async populateTransaction(tx) { + const provider = checkProvider(this, "populateTransaction"); + const pop = await populate(this, tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + // Populate the chain ID + const network = await (this.provider).getNetwork(); + if (pop.chainId != null) { + const chainId = (0,maths/* getBigInt */.Ab)(pop.chainId); + (0,errors/* assertArgument */.MR)(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId); + } + else { + pop.chainId = network.chainId; + } + // Do not allow mixing pre-eip-1559 and eip-1559 properties + const hasEip1559 = (pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null); + if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) { + (0,errors/* assertArgument */.MR)(false, "eip-1559 transaction do not support gasPrice", "tx", tx); + } + else if ((pop.type === 0 || pop.type === 1) && hasEip1559) { + (0,errors/* assertArgument */.MR)(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx); + } + if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) { + // Fully-formed EIP-1559 transaction (skip getFeeData) + pop.type = 2; + } + else if (pop.type === 0 || pop.type === 1) { + // Explicit Legacy or EIP-2930 transaction + // We need to get fee data to determine things + const feeData = await provider.getFeeData(); + (0,errors/* assert */.vA)(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", { + operation: "getGasPrice" + }); + // Populate missing gasPrice + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; + } + } + else { + // We need to get fee data to determine things + const feeData = await provider.getFeeData(); + if (pop.type == null) { + // We need to auto-detect the intended type of this transaction... + if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { + // The network supports EIP-1559! + // Upgrade transaction from null to eip-1559 + pop.type = 2; + if (pop.gasPrice != null) { + // Using legacy gasPrice property on an eip-1559 network, + // so use gasPrice as both fee properties + const gasPrice = pop.gasPrice; + delete pop.gasPrice; + pop.maxFeePerGas = gasPrice; + pop.maxPriorityFeePerGas = gasPrice; + } + else { + // Populate missing fee data + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } + else if (feeData.gasPrice != null) { + // Network doesn't support EIP-1559... + // ...but they are trying to use EIP-1559 properties + (0,errors/* assert */.vA)(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", { + operation: "populateTransaction" + }); + // Populate missing fee data + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; + } + // Explicitly set untyped transaction to legacy + // @TODO: Maybe this shold allow type 1? + pop.type = 0; + } + else { + // getFeeData has failed us. + (0,errors/* assert */.vA)(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", { + operation: "signer.getFeeData" + }); + } + } + else if (pop.type === 2 || pop.type === 3) { + // Explicitly using EIP-1559 or EIP-4844 + // Populate missing fee data + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } + //@TOOD: Don't await all over the place; save them up for + // the end for better batching + return await (0,properties/* resolveProperties */.k)(pop); + } + async estimateGas(tx) { + return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return checkProvider(this, "call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = checkProvider(this, "resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = checkProvider(this, "sendTransaction"); + const pop = await this.populateTransaction(tx); + delete pop.from; + const txObj = transaction/* Transaction */.Z.from(pop); + return await provider.broadcastTransaction(await this.signTransaction(txObj)); + } +} +/** + * A **VoidSigner** is a class deisgned to allow an address to be used + * in any API which accepts a Signer, but for which there are no + * credentials available to perform any actual signing. + * + * This for example allow impersonating an account for the purpose of + * static calls or estimating gas, but does not allow sending transactions. + */ +class VoidSigner extends AbstractSigner { + /** + * The signer address. + */ + address; + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address, provider) { + super(provider); + (0,properties/* defineProperties */.n)(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + (0,errors/* assert */.vA)(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation }); + } + async signTransaction(tx) { + this.#throwUnsupported("transactions", "signTransaction"); + } + async signMessage(message) { + this.#throwUnsupported("messages", "signMessage"); + } + async signTypedData(domain, types, value) { + this.#throwUnsupported("typed-data", "signTypedData"); + } +} +//# sourceMappingURL=abstract-signer.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/subscriber-filterid.js +/* provided dependency */ var subscriber_filterid_console = __webpack_require__(96763); + + +function subscriber_filterid_copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +/** + * Some backends support subscribing to events using a Filter ID. + * + * When subscribing with this technique, the node issues a unique + * //Filter ID//. At this point the node dedicates resources to + * the filter, so that periodic calls to follow up on the //Filter ID// + * will receive any events since the last call. + * + * @_docloc: api/providers/abstract-provider + */ +class FilterIdSubscriber { + #provider; + #filterIdPromise; + #poller; + #running; + #network; + #hault; + /** + * Creates a new **FilterIdSubscriber** which will used [[_subscribe]] + * and [[_emitResults]] to setup the subscription and provide the event + * to the %%provider%%. + */ + constructor(provider) { + this.#provider = provider; + this.#filterIdPromise = null; + this.#poller = this.#poll.bind(this); + this.#running = false; + this.#network = null; + this.#hault = false; + } + /** + * Sub-classes **must** override this to begin the subscription. + */ + _subscribe(provider) { + throw new Error("subclasses must override this"); + } + /** + * Sub-classes **must** override this handle the events. + */ + _emitResults(provider, result) { + throw new Error("subclasses must override this"); + } + /** + * Sub-classes **must** override this handle recovery on errors. + */ + _recover(provider) { + throw new Error("subclasses must override this"); + } + async #poll(blockNumber) { + try { + // Subscribe if necessary + if (this.#filterIdPromise == null) { + this.#filterIdPromise = this._subscribe(this.#provider); + } + // Get the Filter ID + let filterId = null; + try { + filterId = await this.#filterIdPromise; + } + catch (error) { + if (!(0,errors/* isError */.bJ)(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") { + throw error; + } + } + // The backend does not support Filter ID; downgrade to + // polling + if (filterId == null) { + this.#filterIdPromise = null; + this.#provider._recoverSubscriber(this, this._recover(this.#provider)); + return; + } + const network = await this.#provider.getNetwork(); + if (!this.#network) { + this.#network = network; + } + if (this.#network.chainId !== network.chainId) { + throw new Error("chaid changed"); + } + if (this.#hault) { + return; + } + const result = await this.#provider.send("eth_getFilterChanges", [filterId]); + await this._emitResults(this.#provider, result); + } + catch (error) { + subscriber_filterid_console.log("@TODO", error); + } + this.#provider.once("block", this.#poller); + } + #teardown() { + const filterIdPromise = this.#filterIdPromise; + if (filterIdPromise) { + this.#filterIdPromise = null; + filterIdPromise.then((filterId) => { + if (this.#provider.destroyed) { + return; + } + this.#provider.send("eth_uninstallFilter", [filterId]); + }); + } + } + start() { + if (this.#running) { + return; + } + this.#running = true; + this.#poll(-2); + } + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#hault = true; + this.#teardown(); + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#teardown(); + } + this.#provider.off("block", this.#poller); + } + resume() { this.start(); } +} +/** + * A **FilterIdSubscriber** for receiving contract events. + * + * @_docloc: api/providers/abstract-provider + */ +class FilterIdEventSubscriber extends FilterIdSubscriber { + #event; + /** + * Creates a new **FilterIdEventSubscriber** attached to %%provider%% + * listening for %%filter%%. + */ + constructor(provider, filter) { + super(provider); + this.#event = subscriber_filterid_copy(filter); + } + _recover(provider) { + return new PollingEventSubscriber(provider, this.#event); + } + async _subscribe(provider) { + const filterId = await provider.send("eth_newFilter", [this.#event]); + return filterId; + } + async _emitResults(provider, results) { + for (const result of results) { + provider.emit(this.#event, provider._wrapLog(result, provider._network)); + } + } +} +/** + * A **FilterIdSubscriber** for receiving pending transactions events. + * + * @_docloc: api/providers/abstract-provider + */ +class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider) { + return await provider.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider, results) { + for (const result of results) { + provider.emit("pending", result); + } + } +} +//# sourceMappingURL=subscriber-filterid.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/provider-jsonrpc.js +/* provided dependency */ var provider_jsonrpc_console = __webpack_require__(96763); +/** + * One of the most common ways to interact with the blockchain is + * by a node running a JSON-RPC interface which can be connected to, + * based on the transport, using: + * + * - HTTP or HTTPS - [[JsonRpcProvider]] + * - WebSocket - [[WebSocketProvider]] + * - IPC - [[IpcSocketProvider]] + * + * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider] + */ +// @TODO: +// - Add the batching API +// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false + + + + + + + + + + +const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g); +//const Methods = "getAddress,then".split(/,/g); +function deepCopy(value) { + if (value == null || Primitive.indexOf(typeof (value)) >= 0) { + return value; + } + // Keep any Addressable + if (typeof (value.getAddress) === "function") { + return value; + } + if (Array.isArray(value)) { + return (value.map(deepCopy)); + } + if (typeof (value) === "object") { + return Object.keys(value).reduce((accum, key) => { + accum[key] = value[key]; + return accum; + }, {}); + } + throw new Error(`should not happen: ${value} (${typeof (value)})`); +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +function isPollable(value) { + return (value && typeof (value.pollingInterval) === "number"); +} +const provider_jsonrpc_defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100, + cacheTimeout: 250, + pollingInterval: 4000 +}; +// @TODO: Unchecked Signers +class JsonRpcSigner extends AbstractSigner { + address; + constructor(provider, address) { + super(provider); + address = (0,address_address/* getAddress */.b)(address); + (0,properties/* defineProperties */.n)(this, { address }); + } + connect(provider) { + (0,errors/* assert */.vA)(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { + operation: "signer.connect" + }); + } + async getAddress() { + return this.address; + } + // JSON-RPC will automatially fill in nonce, etc. so we just check from + async populateTransaction(tx) { + return await this.populateCall(tx); + } + // Returns just the hash of the transaction after sent, which is what + // the bare JSON-RPC API does; + async sendUncheckedTransaction(_tx) { + const tx = deepCopy(_tx); + const promises = []; + // Make sure the from matches the sender + if (tx.from) { + const _from = tx.from; + promises.push((async () => { + const from = await (0,checks/* resolveAddress */.tG)(_from, this.provider); + (0,errors/* assertArgument */.MR)(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user + // wishes to use this, it is easy to specify explicitly, otherwise + // we look it up for them. + if (tx.gasLimit == null) { + promises.push((async () => { + tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); + })()); + } + // The address may be an ENS name or Addressable + if (tx.to != null) { + const _to = tx.to; + promises.push((async () => { + tx.to = await (0,checks/* resolveAddress */.tG)(_to, this.provider); + })()); + } + // Wait until all of our properties are filled in + if (promises.length) { + await Promise.all(promises); + } + const hexTx = this.provider.getRpcTransaction(tx); + return this.provider.send("eth_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const blockNumber = await this.provider.getBlockNumber(); + // Send the transaction + const hash = await this.sendUncheckedTransaction(tx); + // Unfortunately, JSON-RPC only provides and opaque transaction hash + // for a response, and we need the actual transaction, so we poll + // for it; it should show up very quickly + return await (new Promise((resolve, reject) => { + const timeouts = [1000, 100]; + let invalids = 0; + const checkTx = async () => { + try { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(tx.replaceableTransaction(blockNumber)); + return; + } + } + catch (error) { + // If we were cancelled: stop polling. + // If the data is bad: the node returns bad transactions + // If the network changed: calling again will also fail + // If unsupported: likely destroyed + if ((0,errors/* isError */.bJ)(error, "CANCELLED") || (0,errors/* isError */.bJ)(error, "BAD_DATA") || + (0,errors/* isError */.bJ)(error, "NETWORK_ERROR" || 0)) { + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + reject(error); + return; + } + // Stop-gap for misbehaving backends; see #4513 + if ((0,errors/* isError */.bJ)(error, "INVALID_ARGUMENT")) { + invalids++; + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + if (invalids > 10) { + reject(error); + return; + } + } + // Notify anyone that cares; but we will try again, since + // it is likely an intermittent service error + this.provider.emit("error", (0,errors/* makeError */.xz)("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error })); + } + // Wait another 4 seconds + this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000); + }; + checkTx(); + })); + } + async signTransaction(_tx) { + const tx = deepCopy(_tx); + // Make sure the from matches the sender + if (tx.from) { + const from = await (0,checks/* resolveAddress */.tG)(tx.from, this.provider); + (0,errors/* assertArgument */.MR)(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_signTransaction", [hexTx]); + } + async signMessage(_message) { + const message = ((typeof (_message) === "string") ? (0,utf8/* toUtf8Bytes */.YW)(_message) : _message); + return await this.provider.send("personal_sign", [ + (0,utils_data/* hexlify */.c$)(message), this.address.toLowerCase() + ]); + } + async signTypedData(domain, types, _value) { + const value = deepCopy(_value); + // Populate any ENS names (in-place) + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value) => { + const address = await (0,checks/* resolveAddress */.tG)(value); + (0,errors/* assertArgument */.MR)(address != null, "TypedData does not support null address", "value", value); + return address; + }); + return await this.provider.send("eth_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value)) + ]); + } + async unlock(password) { + return this.provider.send("personal_unlockAccount", [ + this.address.toLowerCase(), password, null + ]); + } + // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? (0,utf8/* toUtf8Bytes */.YW)(_message) : _message); + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), (0,utils_data/* hexlify */.c$)(message) + ]); + } +} +/** + * The JsonRpcApiProvider is an abstract class and **MUST** be + * sub-classed. + * + * It provides the base for all JSON-RPC-based Provider interaction. + * + * Sub-classing Notes: + * - a sub-class MUST override _send + * - a sub-class MUST call the `_start()` method once connected + */ +class JsonRpcApiProvider extends AbstractProvider { + #options; + // The next ID to use for the JSON-RPC ID field + #nextId; + // Payloads are queued and triggered in batches using the drainTimer + #payloads; + #drainTimer; + #notReady; + #network; + #pendingDetectNetwork; + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + // If we aren't using batching, no harm in sending it immediately + const stallTime = (this._getOption("batchMaxCount") === 1) ? 0 : this._getOption("batchStallTime"); + this.#drainTimer = setTimeout(() => { + this.#drainTimer = null; + const payloads = this.#payloads; + this.#payloads = []; + while (payloads.length) { + // Create payload batches that satisfy our batch constraints + const batch = [(payloads.shift())]; + while (payloads.length) { + if (batch.length === this.#options.batchMaxCount) { + break; + } + batch.push((payloads.shift())); + const bytes = JSON.stringify(batch.map((p) => p.payload)); + if (bytes.length > this.#options.batchMaxSize) { + payloads.unshift((batch.pop())); + break; + } + } + // Process the result to each payload + (async () => { + const payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload)); + this.emit("debug", { action: "sendRpcPayload", payload }); + try { + const result = await this._send(payload); + this.emit("debug", { action: "receiveRpcResult", result }); + // Process results in batch order + for (const { resolve, reject, payload } of batch) { + if (this.destroyed) { + reject((0,errors/* makeError */.xz)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + continue; + } + // Find the matching result + const resp = result.filter((r) => (r.id === payload.id))[0]; + // No result; the node failed us in unexpected ways + if (resp == null) { + const error = (0,errors/* makeError */.xz)("missing response for request", "BAD_DATA", { + value: result, info: { payload } + }); + this.emit("error", error); + reject(error); + continue; + } + // The response is an error + if ("error" in resp) { + reject(this.getRpcError(payload, resp)); + continue; + } + // All good; send the result + resolve(resp.result); + } + } + catch (error) { + this.emit("debug", { action: "receiveRpcError", error }); + for (const { reject } of batch) { + // @TODO: augment the error with the payload + reject(error); + } + } + })(); + } + }, stallTime); + } + constructor(network, options) { + super(network, options); + this.#nextId = 1; + this.#options = Object.assign({}, provider_jsonrpc_defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + this.#network = null; + this.#pendingDetectNetwork = null; + { + let resolve = null; + const promise = new Promise((_resolve) => { + resolve = _resolve; + }); + this.#notReady = { promise, resolve }; + } + const staticNetwork = this._getOption("staticNetwork"); + if (typeof (staticNetwork) === "boolean") { + (0,errors/* assertArgument */.MR)(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); + if (staticNetwork && network != null) { + this.#network = Network.from(network); + } + } + else if (staticNetwork) { + // Make sure any static network is compatbile with the provided netwrok + (0,errors/* assertArgument */.MR)(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options); + this.#network = staticNetwork; + } + } + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key) { + return this.#options[key]; + } + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network() { + (0,errors/* assert */.vA)(this.#network, "network is not available yet", "NETWORK_ERROR"); + return this.#network; + } + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + async _perform(req) { + // Legacy networks do not like the type field being passed along (which + // is fair), so we delete type if it is 0 and a non-EIP-1559 network + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && (0,maths/* getBigInt */.Ab)(tx.type)) { + // If there are no EIP-1559 properties, it might be non-EIP-a559 + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = await this.getFeeData(); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + // Network doesn't know about EIP-1559 (and hence type) + req = Object.assign({}, req, { + transaction: Object.assign({}, tx, { type: undefined }) + }); + } + } + } + } + const request = this.getRpcRequest(req); + if (request != null) { + return await this.send(request.method, request.args); + } + return super._perform(req); + } + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + async _detectNetwork() { + const network = this._getOption("staticNetwork"); + if (network) { + if (network === true) { + if (this.#network) { + return this.#network; + } + } + else { + return network; + } + } + if (this.#pendingDetectNetwork) { + return await this.#pendingDetectNetwork; + } + // If we are ready, use ``send``, which enabled requests to be batched + if (this.ready) { + this.#pendingDetectNetwork = (async () => { + try { + const result = Network.from((0,maths/* getBigInt */.Ab)(await this.send("eth_chainId", []))); + this.#pendingDetectNetwork = null; + return result; + } + catch (error) { + this.#pendingDetectNetwork = null; + throw error; + } + })(); + return await this.#pendingDetectNetwork; + } + // We are not ready yet; use the primitive _send + this.#pendingDetectNetwork = (async () => { + const payload = { + id: this.#nextId++, method: "eth_chainId", params: [], jsonrpc: "2.0" + }; + this.emit("debug", { action: "sendRpcPayload", payload }); + let result; + try { + result = (await this._send(payload))[0]; + this.#pendingDetectNetwork = null; + } + catch (error) { + this.#pendingDetectNetwork = null; + this.emit("debug", { action: "receiveRpcError", error }); + throw error; + } + this.emit("debug", { action: "receiveRpcResult", result }); + if ("result" in result) { + return Network.from((0,maths/* getBigInt */.Ab)(result.result)); + } + throw this.getRpcError(payload, result); + })(); + return await this.#pendingDetectNetwork; + } + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start() { + if (this.#notReady == null || this.#notReady.resolve == null) { + return; + } + this.#notReady.resolve(); + this.#notReady = null; + (async () => { + // Bootstrap the network + while (this.#network == null && !this.destroyed) { + try { + this.#network = await this._detectNetwork(); + } + catch (error) { + if (this.destroyed) { + break; + } + provider_jsonrpc_console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + this.emit("error", (0,errors/* makeError */.xz)("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); + await stall(1000); + } + } + // Start dispatching requests + this.#scheduleDrain(); + })(); + } + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + async _waitUntilReady() { + if (this.#notReady == null) { + return; + } + return await this.#notReady.promise; + } + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub) { + // Pending Filters aren't availble via polling + if (sub.type === "pending") { + return new FilterIdPendingSubscriber(this); + } + if (sub.type === "event") { + if (this._getOption("polling")) { + return new PollingEventSubscriber(this, sub.filter); + } + return new FilterIdEventSubscriber(this, sub.filter); + } + // Orphaned Logs are handled automatically, by the filter, since + // logs with removed are emitted by it + if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("orphan"); + } + return super._getSubscriber(sub); + } + /** + * Returns true only if the [[_start]] has been called. + */ + get ready() { return this.#notReady == null; } + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx) { + const result = {}; + // JSON-RPC now requires numeric values to be "quantity" values + ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => { + if (tx[key] == null) { + return; + } + let dstKey = key; + if (key === "gasLimit") { + dstKey = "gas"; + } + result[dstKey] = (0,maths/* toQuantity */.nD)((0,maths/* getBigInt */.Ab)(tx[key], `tx.${key}`)); + }); + // Make sure addresses and data are lowercase + ["from", "to", "data"].forEach((key) => { + if (tx[key] == null) { + return; + } + result[key] = (0,utils_data/* hexlify */.c$)(tx[key]); + }); + // Normalize the access list object + if (tx.accessList) { + result["accessList"] = (0,accesslist/* accessListify */.$)(tx.accessList); + } + return result; + } + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "eth_chainId", args: [] }; + case "getBlockNumber": + return { method: "eth_blockNumber", args: [] }; + case "getGasPrice": + return { method: "eth_gasPrice", args: [] }; + case "getPriorityFee": + return { method: "eth_maxPriorityFeePerGas", args: [] }; + case "getBalance": + return { + method: "eth_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "eth_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorage": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "eth_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "eth_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "eth_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "eth_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + case "getLogs": + if (req.filter && req.filter.address != null) { + if (Array.isArray(req.filter.address)) { + req.filter.address = req.filter.address.map(getLowerCase); + } + else { + req.filter.address = getLowerCase(req.filter.address); + } + } + return { method: "eth_getLogs", args: [req.filter] }; + } + return null; + } + /** + * Returns an ethers-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload, _error) { + const { method } = payload; + const { error } = _error; + if (method === "eth_estimateGas" && error.message) { + const msg = error.message; + if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { + return (0,errors/* makeError */.xz)("insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: (payload.params[0]), + info: { payload, error } + }); + } + } + if (method === "eth_call" || method === "eth_estimateGas") { + const result = spelunkData(error); + const e = abi_coder/* AbiCoder */.y.getBuiltinCallException((method === "eth_call") ? "call" : "estimateGas", (payload.params[0]), (result ? result.data : null)); + e.info = { error, payload }; + return e; + } + // Only estimateGas and call can return arbitrary contract-defined text, so now we + // we can process text safely. + const message = JSON.stringify(spelunkMessage(error)); + if (typeof (error.message) === "string" && error.message.match(/user denied|ethers-user-denied/i)) { + const actionMap = { + eth_sign: "signMessage", + personal_sign: "signMessage", + eth_signTypedData_v4: "signTypedData", + eth_signTransaction: "signTransaction", + eth_sendTransaction: "sendTransaction", + eth_requestAccounts: "requestAccess", + wallet_requestAccounts: "requestAccess", + }; + return (0,errors/* makeError */.xz)(`user rejected action`, "ACTION_REJECTED", { + action: (actionMap[method] || "unknown"), + reason: "rejected", + info: { payload, error } + }); + } + if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") { + const transaction = (payload.params[0]); + if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { + return (0,errors/* makeError */.xz)("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction, info: { error } + }); + } + if (message.match(/nonce/i) && message.match(/too low/i)) { + return (0,errors/* makeError */.xz)("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } }); + } + // "replacement transaction underpriced" + if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { + return (0,errors/* makeError */.xz)("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } }); + } + if (message.match(/only replay-protected/i)) { + return (0,errors/* makeError */.xz)("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction, info: { error } } + }); + } + } + let unsupported = !!message.match(/the method .* does not exist/i); + if (!unsupported) { + if (error && error.details && error.details.startsWith("Unauthorized method:")) { + unsupported = true; + } + } + if (unsupported) { + return (0,errors/* makeError */.xz)("unsupported operation", "UNSUPPORTED_OPERATION", { + operation: payload.method, info: { error, payload } + }); + } + return (0,errors/* makeError */.xz)("could not coalesce error", "UNKNOWN_ERROR", { error, payload }); + } + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method, params) { + // @TODO: cache chainId?? purge on switch_networks + // We have been destroyed; no operations are supported anymore + if (this.destroyed) { + return Promise.reject((0,errors/* makeError */.xz)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method })); + } + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" } + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + async getSigner(address) { + if (address == null) { + address = 0; + } + const accountsPromise = this.send("eth_accounts", []); + // Account index + if (typeof (address) === "number") { + const accounts = (await accountsPromise); + if (address >= accounts.length) { + throw new Error("no such account"); + } + return new JsonRpcSigner(this, accounts[address]); + } + const { accounts } = await (0,properties/* resolveProperties */.k)({ + network: this.getNetwork(), + accounts: accountsPromise + }); + // Account address + address = (0,address_address/* getAddress */.b)(address); + for (const account of accounts) { + if ((0,address_address/* getAddress */.b)(account) === address) { + return new JsonRpcSigner(this, address); + } + } + throw new Error("invalid account"); + } + async listAccounts() { + const accounts = await this.send("eth_accounts", []); + return accounts.map((a) => new JsonRpcSigner(this, a)); + } + destroy() { + // Stop processing requests + if (this.#drainTimer) { + clearTimeout(this.#drainTimer); + this.#drainTimer = null; + } + // Cancel all pending requests + for (const { payload, reject } of this.#payloads) { + reject((0,errors/* makeError */.xz)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + } + this.#payloads = []; + // Parent clean-up + super.destroy(); + } +} +// @TODO: remove this in v7, it is not exported because this functionality +// is exposed in the JsonRpcApiProvider by setting polling to true. It should +// be safe to remove regardless, because it isn't reachable, but just in case. +/** + * @_ignore: + */ +class JsonRpcApiPollingProvider extends JsonRpcApiProvider { + #pollingInterval; + constructor(network, options) { + super(network, options); + this.#pollingInterval = 4000; + } + _getSubscriber(sub) { + const subscriber = super._getSubscriber(sub); + if (isPollable(subscriber)) { + subscriber.pollingInterval = this.#pollingInterval; + } + return subscriber; + } + /** + * The polling interval (default: 4000 ms) + */ + get pollingInterval() { return this.#pollingInterval; } + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); + } + this.#pollingInterval = value; + this._forEachSubscriber((sub) => { + if (isPollable(sub)) { + sub.pollingInterval = this.#pollingInterval; + } + }); + } +} +/** + * The JsonRpcProvider is one of the most common Providers, + * which performs all operations over HTTP (or HTTPS) requests. + * + * Events are processed by polling the backend for the current block + * number; when it advances, all block-base events are then checked + * for updates. + */ +class JsonRpcProvider extends JsonRpcApiPollingProvider { + #connect; + constructor(url, network, options) { + if (url == null) { + url = "http:/\/localhost:8545"; + } + super(network, options); + if (typeof (url) === "string") { + this.#connect = new FetchRequest(url); + } + else { + this.#connect = url.clone(); + } + } + _getConnection() { + return this.#connect.clone(); + } + async send(method, params) { + // All requests are over HTTP, so we can just start handling requests + // We do this here rather than the constructor so that we don't send any + // requests to the network (i.e. eth_chainId) until we absolutely have to. + await this._start(); + return await super.send(method, params); + } + async _send(payload) { + // Configure a POST connection for the requested method + const request = this._getConnection(); + request.body = JSON.stringify(payload); + request.setHeader("content-type", "application/json"); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } +} +function spelunkData(value) { + if (value == null) { + return null; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string" && value.message.match(/revert/i) && (0,utils_data/* isHexString */.Lo)(value.data)) { + return { message: value.message, data: value.data }; + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + const result = spelunkData(value[key]); + if (result) { + return result; + } + } + return null; + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return spelunkData(JSON.parse(value)); + } + catch (error) { } + } + return null; +} +function _spelunkMessage(value, result) { + if (value == null) { + return; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string") { + result.push(value.message); + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + _spelunkMessage(value[key], result); + } + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return _spelunkMessage(JSON.parse(value), result); + } + catch (error) { } + } +} +function spelunkMessage(value) { + const result = []; + _spelunkMessage(value, result); + return result; +} +//# sourceMappingURL=provider-jsonrpc.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/signing-key.js + 6 modules +var signing_key = __webpack_require__(15496); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/constants/strings.js +// NFKC (composed) // (decomposed) +/** + * A constant for the ether symbol (normalized using NFKC). + * + * (**i.e.** ``"\\u039e"``) + */ +const EtherSymbol = "\u039e"; // "\uD835\uDF63"; +/** + * A constant for the [[link-eip-191]] personal message prefix. + * + * (**i.e.** ``"\\x19Ethereum Signed Message:\\n"``) + */ +const MessagePrefix = "\x19Ethereum Signed Message:\n"; +//# sourceMappingURL=strings.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/hash/message.js + + + + +/** + * Computes the [[link-eip-191]] personal-sign message digest to sign. + * + * This prefixes the message with [[MessagePrefix]] and the decimal length + * of %%message%% and computes the [[keccak256]] digest. + * + * If %%message%% is a string, it is converted to its UTF-8 bytes + * first. To compute the digest of a [[DataHexString]], it must be converted + * to [bytes](getBytes). + * + * @example: + * hashMessage("Hello World") + * //_result: + * + * // Hashes the SIX (6) string characters, i.e. + * // [ "0", "x", "4", "2", "4", "3" ] + * hashMessage("0x4243") + * //_result: + * + * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]... + * hashMessage(getBytes("0x4243")) + * //_result: + * + * // ...which is equal to using data + * hashMessage(new Uint8Array([ 0x42, 0x43 ])) + * //_result: + * + */ +function hashMessage(message) { + if (typeof (message) === "string") { + message = (0,utf8/* toUtf8Bytes */.YW)(message); + } + return (0,keccak/* keccak256 */.S)((0,utils_data/* concat */.xW)([ + (0,utf8/* toUtf8Bytes */.YW)(MessagePrefix), + (0,utf8/* toUtf8Bytes */.YW)(String(message.length)), + message + ])); +} +/** + * Return the address of the private key that produced + * the signature %%sig%% during signing for %%message%%. + */ +function verifyMessage(message, sig) { + const digest = hashMessage(message); + return recoverAddress(digest, sig); +} +//# sourceMappingURL=message.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/transaction/address.js +var transaction_address = __webpack_require__(20415); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/base-wallet.js + + + + + +/** + * The **BaseWallet** is a stream-lined implementation of a + * [[Signer]] that operates with a private key. + * + * It is preferred to use the [[Wallet]] class, as it offers + * additional functionality and simplifies loading a variety + * of JSON formats, Mnemonic Phrases, etc. + * + * This class may be of use for those attempting to implement + * a minimal Signer. + */ +class BaseWallet extends AbstractSigner { + /** + * The wallet address. + */ + address; + #signingKey; + /** + * Creates a new BaseWallet for %%privateKey%%, optionally + * connected to %%provider%%. + * + * If %%provider%% is not specified, only offline methods can + * be used. + */ + constructor(privateKey, provider) { + super(provider); + (0,errors/* assertArgument */.MR)(privateKey && typeof (privateKey.sign) === "function", "invalid private key", "privateKey", "[ REDACTED ]"); + this.#signingKey = privateKey; + const address = (0,transaction_address/* computeAddress */.K)(this.signingKey.publicKey); + (0,properties/* defineProperties */.n)(this, { address }); + } + // Store private values behind getters to reduce visibility + // in console.log + /** + * The [[SigningKey]] used for signing payloads. + */ + get signingKey() { return this.#signingKey; } + /** + * The private key for this wallet. + */ + get privateKey() { return this.signingKey.privateKey; } + async getAddress() { return this.address; } + connect(provider) { + return new BaseWallet(this.#signingKey, provider); + } + async signTransaction(tx) { + // Replace any Addressable or ENS name with an address + const { to, from } = await (0,properties/* resolveProperties */.k)({ + to: (tx.to ? (0,checks/* resolveAddress */.tG)(tx.to, this.provider) : undefined), + from: (tx.from ? (0,checks/* resolveAddress */.tG)(tx.from, this.provider) : undefined) + }); + if (to != null) { + tx.to = to; + } + if (from != null) { + tx.from = from; + } + if (tx.from != null) { + (0,errors/* assertArgument */.MR)((0,address_address/* getAddress */.b)((tx.from)) === this.address, "transaction from address mismatch", "tx.from", tx.from); + delete tx.from; + } + // Build the transaction + const btx = transaction/* Transaction */.Z.from(tx); + btx.signature = this.signingKey.sign(btx.unsignedHash); + return btx.serialized; + } + async signMessage(message) { + return this.signMessageSync(message); + } + // @TODO: Add a secialized signTx and signTyped sync that enforces + // all parameters are known? + /** + * Returns the signature for %%message%% signed with this wallet. + */ + signMessageSync(message) { + return this.signingKey.sign(hashMessage(message)).serialized; + } + async signTypedData(domain, types, value) { + // Populate any ENS names + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => { + // @TODO: this should use resolveName; addresses don't + // need a provider + (0,errors/* assert */.vA)(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + const address = await this.provider.resolveName(name); + (0,errors/* assert */.vA)(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name + }); + return address; + }); + return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized; + } +} +//# sourceMappingURL=base-wallet.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/sha2.js +var sha2 = __webpack_require__(68650); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/crypto-browser.js + 1 modules +var crypto_browser = __webpack_require__(8180); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/hmac.js +/** + * An **HMAC** enables verification that a given key was used + * to authenticate a payload. + * + * See: [[link-wiki-hmac]] + * + * @_subsection: api/crypto:HMAC [about-hmac] + */ + + +let hmac_locked = false; +const _computeHmac = function (algorithm, key, data) { + return (0,crypto_browser/* createHmac */.Gz)(algorithm, key).update(data).digest(); +}; +let __computeHmac = _computeHmac; +/** + * Return the HMAC for %%data%% using the %%key%% key with the underlying + * %%algo%% used for compression. + * + * @example: + * key = id("some-secret") + * + * // Compute the HMAC + * computeHmac("sha256", key, "0x1337") + * //_result: + * + * // To compute the HMAC of UTF-8 data, the data must be + * // converted to UTF-8 bytes + * computeHmac("sha256", key, toUtf8Bytes("Hello World")) + * //_result: + * + */ +function computeHmac(algorithm, _key, _data) { + const key = (0,utils_data/* getBytes */.q5)(_key, "key"); + const data = (0,utils_data/* getBytes */.q5)(_data, "data"); + return (0,utils_data/* hexlify */.c$)(__computeHmac(algorithm, key, data)); +} +computeHmac._ = _computeHmac; +computeHmac.lock = function () { hmac_locked = true; }; +computeHmac.register = function (func) { + if (hmac_locked) { + throw new Error("computeHmac is locked"); + } + __computeHmac = func; +}; +Object.freeze(computeHmac); +//# sourceMappingURL=hmac.js.map +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_sha2.js +var _sha2 = __webpack_require__(37171); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/utils.js + 1 modules +var utils = __webpack_require__(10750); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/ripemd160.js + + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends _sha2/* SHA2 */.D { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160 = /* @__PURE__ */ (0,utils/* wrapConstructor */.ld)(() => new RIPEMD160()); +//# sourceMappingURL=ripemd160.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/ripemd160.js + + +let ripemd160_locked = false; +const _ripemd160 = function (data) { + return ripemd160(data); +}; +let __ripemd160 = _ripemd160; +/** + * Compute the cryptographic RIPEMD-160 hash of %%data%%. + * + * @_docloc: api/crypto:Hash Functions + * @returns DataHexstring + * + * @example: + * ripemd160("0x") + * //_result: + * + * ripemd160("0x1337") + * //_result: + * + * ripemd160(new Uint8Array([ 0x13, 0x37 ])) + * //_result: + * + */ +function ripemd160_ripemd160(_data) { + const data = (0,utils_data/* getBytes */.q5)(_data, "data"); + return (0,utils_data/* hexlify */.c$)(__ripemd160(data)); +} +ripemd160_ripemd160._ = _ripemd160; +ripemd160_ripemd160.lock = function () { ripemd160_locked = true; }; +ripemd160_ripemd160.register = function (func) { + if (ripemd160_locked) { + throw new TypeError("ripemd160 is locked"); + } + __ripemd160 = func; +}; +Object.freeze(ripemd160_ripemd160); +//# sourceMappingURL=ripemd160.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/random.js +/** + * A **Cryptographically Secure Random Value** is one that has been + * generated with additional care take to prevent side-channels + * from allowing others to detect it and prevent others from through + * coincidence generate the same values. + * + * @_subsection: api/crypto:Random Values [about-crypto-random] + */ + +let random_locked = false; +const _randomBytes = function (length) { + return new Uint8Array((0,crypto_browser/* randomBytes */.po)(length)); +}; +let __randomBytes = _randomBytes; +/** + * Return %%length%% bytes of cryptographically secure random data. + * + * @example: + * randomBytes(8) + * //_result: + */ +function randomBytes(length) { + return __randomBytes(length); +} +randomBytes._ = _randomBytes; +randomBytes.lock = function () { random_locked = true; }; +randomBytes.register = function (func) { + if (random_locked) { + throw new Error("randomBytes is locked"); + } + __randomBytes = func; +}; +Object.freeze(randomBytes); +//# sourceMappingURL=random.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/wordlists/lang-en.js + 3 modules +var lang_en = __webpack_require__(24636); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/wallet/mnemonic.js +var wallet_mnemonic = __webpack_require__(37514); +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/aes.js +/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ +var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _AES_key, _AES_Kd, _AES_Ke; +// Number of rounds by keysize +const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; +// Round constant words +const rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]; +// S-box and Inverse S-box (S is for Substitution) +const S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]; +const Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]; +// Transformations for encryption +const T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a]; +const T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616]; +const T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16]; +const T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c]; +// Transformations for decryption +const T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742]; +const T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857]; +const T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8]; +const T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0]; +// Transformations for decryption key expansion +const U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]; +const U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697]; +const U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46]; +const U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d]; +function convertToInt32(bytes) { + const result = []; + for (let i = 0; i < bytes.length; i += 4) { + result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); + } + return result; +} +class AES { + get key() { return __classPrivateFieldGet(this, _AES_key, "f").slice(); } + constructor(key) { + _AES_key.set(this, void 0); + _AES_Kd.set(this, void 0); + _AES_Ke.set(this, void 0); + if (!(this instanceof AES)) { + throw Error('AES must be instanitated with `new`'); + } + __classPrivateFieldSet(this, _AES_key, new Uint8Array(key), "f"); + const rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)'); + } + // encryption round keys + __classPrivateFieldSet(this, _AES_Ke, [], "f"); + // decryption round keys + __classPrivateFieldSet(this, _AES_Kd, [], "f"); + for (let i = 0; i <= rounds; i++) { + __classPrivateFieldGet(this, _AES_Ke, "f").push([0, 0, 0, 0]); + __classPrivateFieldGet(this, _AES_Kd, "f").push([0, 0, 0, 0]); + } + const roundKeyCount = (rounds + 1) * 4; + const KC = this.key.length / 4; + // convert the key into ints + const tk = convertToInt32(this.key); + // copy values into round key arrays + let index; + for (let i = 0; i < KC; i++) { + index = i >> 2; + __classPrivateFieldGet(this, _AES_Ke, "f")[index][i % 4] = tk[i]; + __classPrivateFieldGet(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i]; + } + // key expansion (fips-197 section 5.2) + let rconpointer = 0; + let t = KC, tt; + while (t < roundKeyCount) { + tt = tk[KC - 1]; + tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^ + (S[(tt >> 8) & 0xFF] << 16) ^ + (S[tt & 0xFF] << 8) ^ + S[(tt >> 24) & 0xFF] ^ + (rcon[rconpointer] << 24)); + rconpointer += 1; + // key expansion (for non-256 bit) + if (KC != 8) { + for (let i = 1; i < KC; i++) { + tk[i] ^= tk[i - 1]; + } + // key expansion for 256-bit keys is "slightly different" (fips-197) + } + else { + for (let i = 1; i < (KC / 2); i++) { + tk[i] ^= tk[i - 1]; + } + tt = tk[(KC / 2) - 1]; + tk[KC / 2] ^= (S[tt & 0xFF] ^ + (S[(tt >> 8) & 0xFF] << 8) ^ + (S[(tt >> 16) & 0xFF] << 16) ^ + (S[(tt >> 24) & 0xFF] << 24)); + for (let i = (KC / 2) + 1; i < KC; i++) { + tk[i] ^= tk[i - 1]; + } + } + // copy values into round key arrays + let i = 0, r, c; + while (i < KC && t < roundKeyCount) { + r = t >> 2; + c = t % 4; + __classPrivateFieldGet(this, _AES_Ke, "f")[r][c] = tk[i]; + __classPrivateFieldGet(this, _AES_Kd, "f")[rounds - r][c] = tk[i++]; + t++; + } + } + // inverse-cipher-ify the decryption round key (fips-197 section 5.3) + for (let r = 1; r < rounds; r++) { + for (let c = 0; c < 4; c++) { + tt = __classPrivateFieldGet(this, _AES_Kd, "f")[r][c]; + __classPrivateFieldGet(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^ + U2[(tt >> 16) & 0xFF] ^ + U3[(tt >> 8) & 0xFF] ^ + U4[tt & 0xFF]); + } + } + } + encrypt(plaintext) { + if (plaintext.length != 16) { + throw new TypeError('invalid plaintext size (must be 16 bytes)'); + } + const rounds = __classPrivateFieldGet(this, _AES_Ke, "f").length - 1; + const a = [0, 0, 0, 0]; + // convert plaintext to (ints ^ key) + let t = convertToInt32(plaintext); + for (let i = 0; i < 4; i++) { + t[i] ^= __classPrivateFieldGet(this, _AES_Ke, "f")[0][i]; + } + // apply round transforms + for (let r = 1; r < rounds; r++) { + for (let i = 0; i < 4; i++) { + a[i] = (T1[(t[i] >> 24) & 0xff] ^ + T2[(t[(i + 1) % 4] >> 16) & 0xff] ^ + T3[(t[(i + 2) % 4] >> 8) & 0xff] ^ + T4[t[(i + 3) % 4] & 0xff] ^ + __classPrivateFieldGet(this, _AES_Ke, "f")[r][i]); + } + t = a.slice(); + } + // the last round is special + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet(this, _AES_Ke, "f")[rounds][i]; + result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; + result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; + result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; + result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff; + } + return result; + } + decrypt(ciphertext) { + if (ciphertext.length != 16) { + throw new TypeError('invalid ciphertext size (must be 16 bytes)'); + } + const rounds = __classPrivateFieldGet(this, _AES_Kd, "f").length - 1; + const a = [0, 0, 0, 0]; + // convert plaintext to (ints ^ key) + let t = convertToInt32(ciphertext); + for (let i = 0; i < 4; i++) { + t[i] ^= __classPrivateFieldGet(this, _AES_Kd, "f")[0][i]; + } + // apply round transforms + for (let r = 1; r < rounds; r++) { + for (let i = 0; i < 4; i++) { + a[i] = (T5[(t[i] >> 24) & 0xff] ^ + T6[(t[(i + 3) % 4] >> 16) & 0xff] ^ + T7[(t[(i + 2) % 4] >> 8) & 0xff] ^ + T8[t[(i + 1) % 4] & 0xff] ^ + __classPrivateFieldGet(this, _AES_Kd, "f")[r][i]); + } + t = a.slice(); + } + // the last round is special + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet(this, _AES_Kd, "f")[rounds][i]; + result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; + result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; + result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; + result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff; + } + return result; + } +} +_AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap(); +//# sourceMappingURL=aes.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode.js + +class ModeOfOperation { + constructor(name, key, cls) { + if (cls && !(this instanceof cls)) { + throw new Error(`${name} must be instantiated with "new"`); + } + Object.defineProperties(this, { + aes: { enumerable: true, value: new AES(key) }, + name: { enumerable: true, value: name } + }); + } +} +//# sourceMappingURL=mode.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode-cbc.js +// Cipher Block Chaining +var mode_cbc_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var mode_cbc_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CBC_iv, _CBC_lastBlock; + +class CBC extends ModeOfOperation { + constructor(key, iv) { + super("ECC", key, CBC); + _CBC_iv.set(this, void 0); + _CBC_lastBlock.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + mode_cbc_classPrivateFieldSet(this, _CBC_iv, new Uint8Array(iv), "f"); + } + else { + mode_cbc_classPrivateFieldSet(this, _CBC_iv, new Uint8Array(16), "f"); + } + mode_cbc_classPrivateFieldSet(this, _CBC_lastBlock, this.iv, "f"); + } + get iv() { return new Uint8Array(mode_cbc_classPrivateFieldGet(this, _CBC_iv, "f")); } + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const ciphertext = new Uint8Array(plaintext.length); + for (let i = 0; i < plaintext.length; i += 16) { + for (let j = 0; j < 16; j++) { + mode_cbc_classPrivateFieldGet(this, _CBC_lastBlock, "f")[j] ^= plaintext[i + j]; + } + mode_cbc_classPrivateFieldSet(this, _CBC_lastBlock, this.aes.encrypt(mode_cbc_classPrivateFieldGet(this, _CBC_lastBlock, "f")), "f"); + ciphertext.set(mode_cbc_classPrivateFieldGet(this, _CBC_lastBlock, "f"), i); + } + return ciphertext; + } + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + const plaintext = new Uint8Array(ciphertext.length); + for (let i = 0; i < ciphertext.length; i += 16) { + const block = this.aes.decrypt(ciphertext.subarray(i, i + 16)); + for (let j = 0; j < 16; j++) { + plaintext[i + j] = block[j] ^ mode_cbc_classPrivateFieldGet(this, _CBC_lastBlock, "f")[j]; + mode_cbc_classPrivateFieldGet(this, _CBC_lastBlock, "f")[j] = ciphertext[i + j]; + } + } + return plaintext; + } +} +_CBC_iv = new WeakMap(), _CBC_lastBlock = new WeakMap(); +//# sourceMappingURL=mode-cbc.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode-cfb.js +// Cipher Feedback +var mode_cfb_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var mode_cfb_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CFB_instances, _CFB_iv, _CFB_shiftRegister, _CFB_shift; + +class CFB extends ModeOfOperation { + constructor(key, iv, segmentSize = 8) { + super("CFB", key, CFB); + _CFB_instances.add(this); + _CFB_iv.set(this, void 0); + _CFB_shiftRegister.set(this, void 0); + // This library currently only handles byte-aligned segmentSize + if (!Number.isInteger(segmentSize) || (segmentSize % 8)) { + throw new TypeError("invalid segmentSize"); + } + Object.defineProperties(this, { + segmentSize: { enumerable: true, value: segmentSize } + }); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + mode_cfb_classPrivateFieldSet(this, _CFB_iv, new Uint8Array(iv), "f"); + } + else { + mode_cfb_classPrivateFieldSet(this, _CFB_iv, new Uint8Array(16), "f"); + } + mode_cfb_classPrivateFieldSet(this, _CFB_shiftRegister, this.iv, "f"); + } + get iv() { return new Uint8Array(mode_cfb_classPrivateFieldGet(this, _CFB_iv, "f")); } + encrypt(plaintext) { + if (8 * plaintext.length % this.segmentSize) { + throw new TypeError("invalid plaintext size (must be multiple of segmentSize bytes)"); + } + const segmentSize = this.segmentSize / 8; + const ciphertext = new Uint8Array(plaintext); + for (let i = 0; i < ciphertext.length; i += segmentSize) { + const xorSegment = this.aes.encrypt(mode_cfb_classPrivateFieldGet(this, _CFB_shiftRegister, "f")); + for (let j = 0; j < segmentSize; j++) { + ciphertext[i + j] ^= xorSegment[j]; + } + mode_cfb_classPrivateFieldGet(this, _CFB_instances, "m", _CFB_shift).call(this, ciphertext.subarray(i)); + } + return ciphertext; + } + decrypt(ciphertext) { + if (8 * ciphertext.length % this.segmentSize) { + throw new TypeError("invalid ciphertext size (must be multiple of segmentSize bytes)"); + } + const segmentSize = this.segmentSize / 8; + const plaintext = new Uint8Array(ciphertext); + for (let i = 0; i < plaintext.length; i += segmentSize) { + const xorSegment = this.aes.encrypt(mode_cfb_classPrivateFieldGet(this, _CFB_shiftRegister, "f")); + for (let j = 0; j < segmentSize; j++) { + plaintext[i + j] ^= xorSegment[j]; + } + mode_cfb_classPrivateFieldGet(this, _CFB_instances, "m", _CFB_shift).call(this, ciphertext.subarray(i)); + } + return plaintext; + } +} +_CFB_iv = new WeakMap(), _CFB_shiftRegister = new WeakMap(), _CFB_instances = new WeakSet(), _CFB_shift = function _CFB_shift(data) { + const segmentSize = this.segmentSize / 8; + // Shift the register + mode_cfb_classPrivateFieldGet(this, _CFB_shiftRegister, "f").set(mode_cfb_classPrivateFieldGet(this, _CFB_shiftRegister, "f").subarray(segmentSize)); + mode_cfb_classPrivateFieldGet(this, _CFB_shiftRegister, "f").set(data.subarray(0, segmentSize), 16 - segmentSize); +}; +//# sourceMappingURL=mode-cfb.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode-ctr.js +// Counter Mode +var mode_ctr_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var mode_ctr_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; + +class CTR extends ModeOfOperation { + constructor(key, initialValue) { + super("CTR", key, CTR); + // Remaining bytes for the one-time pad + _CTR_remaining.set(this, void 0); + _CTR_remainingIndex.set(this, void 0); + // The current counter + _CTR_counter.set(this, void 0); + mode_ctr_classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); + mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f").fill(0); + mode_ctr_classPrivateFieldSet(this, _CTR_remaining, mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f"), "f"); // This will be discarded immediately + mode_ctr_classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); + if (initialValue == null) { + initialValue = 1; + } + if (typeof (initialValue) === "number") { + this.setCounterValue(initialValue); + } + else { + this.setCounterBytes(initialValue); + } + } + get counter() { return new Uint8Array(mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")); } + setCounterValue(value) { + if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { + throw new TypeError("invalid counter initial integer value"); + } + for (let index = 15; index >= 0; --index) { + mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256; + value = Math.floor(value / 256); + } + } + setCounterBytes(value) { + if (value.length !== 16) { + throw new TypeError("invalid counter initial Uint8Array value length"); + } + mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f").set(value); + } + increment() { + for (let i = 15; i >= 0; i--) { + if (mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) { + mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0; + } + else { + mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")[i]++; + break; + } + } + } + encrypt(plaintext) { + var _a, _b; + const crypttext = new Uint8Array(plaintext); + for (let i = 0; i < crypttext.length; i++) { + if (mode_ctr_classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) { + mode_ctr_classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(mode_ctr_classPrivateFieldGet(this, _CTR_counter, "f")), "f"); + mode_ctr_classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); + this.increment(); + } + crypttext[i] ^= mode_ctr_classPrivateFieldGet(this, _CTR_remaining, "f")[mode_ctr_classPrivateFieldSet(this, _CTR_remainingIndex, (_b = mode_ctr_classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a]; + } + return crypttext; + } + decrypt(ciphertext) { + return this.encrypt(ciphertext); + } +} +_CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap(); +//# sourceMappingURL=mode-ctr.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode-ecb.js +// Electronic Code Book + +class ECB extends ModeOfOperation { + constructor(key) { + super("ECB", key, ECB); + } + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const crypttext = new Uint8Array(plaintext.length); + for (let i = 0; i < plaintext.length; i += 16) { + crypttext.set(this.aes.encrypt(plaintext.subarray(i, i + 16)), i); + } + return crypttext; + } + decrypt(crypttext) { + if (crypttext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + const plaintext = new Uint8Array(crypttext.length); + for (let i = 0; i < crypttext.length; i += 16) { + plaintext.set(this.aes.decrypt(crypttext.subarray(i, i + 16)), i); + } + return plaintext; + } +} +//# sourceMappingURL=mode-ecb.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/mode-ofb.js +// Output Feedback +var mode_ofb_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var mode_ofb_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _OFB_iv, _OFB_lastPrecipher, _OFB_lastPrecipherIndex; + +class OFB extends ModeOfOperation { + constructor(key, iv) { + super("OFB", key, OFB); + _OFB_iv.set(this, void 0); + _OFB_lastPrecipher.set(this, void 0); + _OFB_lastPrecipherIndex.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + mode_ofb_classPrivateFieldSet(this, _OFB_iv, new Uint8Array(iv), "f"); + } + else { + mode_ofb_classPrivateFieldSet(this, _OFB_iv, new Uint8Array(16), "f"); + } + mode_ofb_classPrivateFieldSet(this, _OFB_lastPrecipher, this.iv, "f"); + mode_ofb_classPrivateFieldSet(this, _OFB_lastPrecipherIndex, 16, "f"); + } + get iv() { return new Uint8Array(mode_ofb_classPrivateFieldGet(this, _OFB_iv, "f")); } + encrypt(plaintext) { + var _a, _b; + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const ciphertext = new Uint8Array(plaintext); + for (let i = 0; i < ciphertext.length; i++) { + if (mode_ofb_classPrivateFieldGet(this, _OFB_lastPrecipherIndex, "f") === 16) { + mode_ofb_classPrivateFieldSet(this, _OFB_lastPrecipher, this.aes.encrypt(mode_ofb_classPrivateFieldGet(this, _OFB_lastPrecipher, "f")), "f"); + mode_ofb_classPrivateFieldSet(this, _OFB_lastPrecipherIndex, 0, "f"); + } + ciphertext[i] ^= mode_ofb_classPrivateFieldGet(this, _OFB_lastPrecipher, "f")[mode_ofb_classPrivateFieldSet(this, _OFB_lastPrecipherIndex, (_b = mode_ofb_classPrivateFieldGet(this, _OFB_lastPrecipherIndex, "f"), _a = _b++, _b), "f"), _a]; + } + return ciphertext; + } + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + return this.encrypt(ciphertext); + } +} +_OFB_iv = new WeakMap(), _OFB_lastPrecipher = new WeakMap(), _OFB_lastPrecipherIndex = new WeakMap(); +//# sourceMappingURL=mode-ofb.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/padding.js +function pkcs7Pad(data) { + const padder = 16 - (data.length % 16); + const result = new Uint8Array(data.length + padder); + result.set(data); + for (let i = data.length; i < result.length; i++) { + result[i] = padder; + } + return result; +} +function pkcs7Strip(data) { + if (data.length < 16) { + throw new TypeError('PKCS#7 invalid length'); + } + const padder = data[data.length - 1]; + if (padder > 16) { + throw new TypeError('PKCS#7 padding byte out of range'); + } + const length = data.length - padder; + for (let i = 0; i < padder; i++) { + if (data[length + i] !== padder) { + throw new TypeError('PKCS#7 invalid padding byte'); + } + } + return new Uint8Array(data.subarray(0, length)); +} +//# sourceMappingURL=padding.js.map +;// CONCATENATED MODULE: ./node_modules/aes-js/lib.esm/index.js + + + + + + + + +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/pbkdf2.js +var pbkdf2 = __webpack_require__(29851); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_assert.js +var _assert = __webpack_require__(27125); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/sha256.js +var sha256 = __webpack_require__(3439); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/pbkdf2.js +var esm_pbkdf2 = __webpack_require__(84877); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/scrypt.js + + + + +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const scrypt_rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= scrypt_rotl(x00 + x12 | 0, 7); + x08 ^= scrypt_rotl(x04 + x00 | 0, 9); + x12 ^= scrypt_rotl(x08 + x04 | 0, 13); + x00 ^= scrypt_rotl(x12 + x08 | 0, 18); + x09 ^= scrypt_rotl(x05 + x01 | 0, 7); + x13 ^= scrypt_rotl(x09 + x05 | 0, 9); + x01 ^= scrypt_rotl(x13 + x09 | 0, 13); + x05 ^= scrypt_rotl(x01 + x13 | 0, 18); + x14 ^= scrypt_rotl(x10 + x06 | 0, 7); + x02 ^= scrypt_rotl(x14 + x10 | 0, 9); + x06 ^= scrypt_rotl(x02 + x14 | 0, 13); + x10 ^= scrypt_rotl(x06 + x02 | 0, 18); + x03 ^= scrypt_rotl(x15 + x11 | 0, 7); + x07 ^= scrypt_rotl(x03 + x15 | 0, 9); + x11 ^= scrypt_rotl(x07 + x03 | 0, 13); + x15 ^= scrypt_rotl(x11 + x07 | 0, 18); + x01 ^= scrypt_rotl(x00 + x03 | 0, 7); + x02 ^= scrypt_rotl(x01 + x00 | 0, 9); + x03 ^= scrypt_rotl(x02 + x01 | 0, 13); + x00 ^= scrypt_rotl(x03 + x02 | 0, 18); + x06 ^= scrypt_rotl(x05 + x04 | 0, 7); + x07 ^= scrypt_rotl(x06 + x05 | 0, 9); + x04 ^= scrypt_rotl(x07 + x06 | 0, 13); + x05 ^= scrypt_rotl(x04 + x07 | 0, 18); + x11 ^= scrypt_rotl(x10 + x09 | 0, 7); + x08 ^= scrypt_rotl(x11 + x10 | 0, 9); + x09 ^= scrypt_rotl(x08 + x11 | 0, 13); + x10 ^= scrypt_rotl(x09 + x08 | 0, 18); + x12 ^= scrypt_rotl(x15 + x14 | 0, 7); + x13 ^= scrypt_rotl(x12 + x15 | 0, 9); + x14 ^= scrypt_rotl(x13 + x12 | 0, 13); + x15 ^= scrypt_rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = (0,utils/* checkOpts */.tY)({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + (0,_assert/* number */.ai)(N); + (0,_assert/* number */.ai)(r); + (0,_assert/* number */.ai)(p); + (0,_assert/* number */.ai)(dkLen); + (0,_assert/* number */.ai)(asyncTick); + (0,_assert/* number */.ai)(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = (0,esm_pbkdf2/* pbkdf2 */.A)(sha256/* sha256 */.s, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = (0,utils/* u32 */.DH)(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = (0,utils/* u32 */.DH)(new Uint8Array(blockSize * N)); + const tmp = (0,utils/* u32 */.DH)(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = (0,esm_pbkdf2/* pbkdf2 */.A)(sha256/* sha256 */.s, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await (0,utils/* asyncLoop */.$h)(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await (0,utils/* asyncLoop */.$h)(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/scrypt.js + + +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { + return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress }); +}; +const _scryptSync = function (passwd, salt, N, r, p, dkLen) { + return scrypt(passwd, salt, { N, r, p, dkLen }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +/** + * The [[link-wiki-scrypt]] uses a memory and cpu hard method of + * derivation to increase the resource cost to brute-force a password + * for a given key. + * + * This means this algorithm is intentionally slow, and can be tuned to + * become slower. As computation and memory speed improve over time, + * increasing the difficulty maintains the cost of an attacker. + * + * For example, if a target time of 5 seconds is used, a legitimate user + * which knows their password requires only 5 seconds to unlock their + * account. A 6 character password has 68 billion possibilities, which + * would require an attacker to invest over 10,000 years of CPU time. This + * is of course a crude example (as password generally aren't random), + * but demonstrates to value of imposing large costs to decryption. + * + * For this reason, if building a UI which involved decrypting or + * encrypting datsa using scrypt, it is recommended to use a + * [[ProgressCallback]] (as event short periods can seem lik an eternity + * if the UI freezes). Including the phrase //"decrypting"// in the UI + * can also help, assuring the user their waiting is for a good reason. + * + * @_docloc: api/crypto:Passwords + * + * @example: + * // The password must be converted to bytes, and it is generally + * // best practices to ensure the string has been normalized. Many + * // formats explicitly indicate the normalization form to use. + * password = "hello" + * passwordBytes = toUtf8Bytes(password, "NFKC") + * + * salt = id("some-salt") + * + * // Compute the scrypt + * scrypt(passwordBytes, salt, 1024, 8, 1, 16) + * //_result: + */ +async function scrypt_scrypt(_passwd, _salt, N, r, p, dkLen, progress) { + const passwd = (0,utils_data/* getBytes */.q5)(_passwd, "passwd"); + const salt = (0,utils_data/* getBytes */.q5)(_salt, "salt"); + return (0,utils_data/* hexlify */.c$)(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); +} +scrypt_scrypt._ = _scryptAsync; +scrypt_scrypt.lock = function () { lockedAsync = true; }; +scrypt_scrypt.register = function (func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); + } + __scryptAsync = func; +}; +Object.freeze(scrypt_scrypt); +/** + * Provides a synchronous variant of [[scrypt]]. + * + * This will completely lock up and freeze the UI in a browser and will + * prevent any event loop from progressing. For this reason, it is + * preferred to use the [async variant](scrypt). + * + * @_docloc: api/crypto:Passwords + * + * @example: + * // The password must be converted to bytes, and it is generally + * // best practices to ensure the string has been normalized. Many + * // formats explicitly indicate the normalization form to use. + * password = "hello" + * passwordBytes = toUtf8Bytes(password, "NFKC") + * + * salt = id("some-salt") + * + * // Compute the scrypt + * scryptSync(passwordBytes, salt, 1024, 8, 1, 16) + * //_result: + */ +function scryptSync(_passwd, _salt, N, r, p, dkLen) { + const passwd = (0,utils_data/* getBytes */.q5)(_passwd, "passwd"); + const salt = (0,utils_data/* getBytes */.q5)(_salt, "salt"); + return (0,utils_data/* hexlify */.c$)(__scryptSync(passwd, salt, N, r, p, dkLen)); +} +scryptSync._ = _scryptSync; +scryptSync.lock = function () { lockedSync = true; }; +scryptSync.register = function (func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); + } + __scryptSync = func; +}; +Object.freeze(scryptSync); +//# sourceMappingURL=scrypt.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/uuid.js +/** + * Explain UUID and link to RFC here. + * + * @_subsection: api/utils:UUID [about-uuid] + */ + +/** + * Returns the version 4 [[link-uuid]] for the %%randomBytes%%. + * + * @see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) + */ +function uuidV4(randomBytes) { + const bytes = (0,utils_data/* getBytes */.q5)(randomBytes, "randomBytes"); + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const value = (0,utils_data/* hexlify */.c$)(bytes); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34), + ].join("-"); +} +//# sourceMappingURL=uuid.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/utils.js +/** + * @_ignore + */ + +function looseArrayify(hexString) { + if (typeof (hexString) === "string" && !hexString.startsWith("0x")) { + hexString = "0x" + hexString; + } + return (0,utils_data/* getBytesCopy */.Lm)(hexString); +} +function zpad(value, length) { + value = String(value); + while (value.length < length) { + value = '0' + value; + } + return value; +} +function getPassword(password) { + if (typeof (password) === 'string') { + return (0,utf8/* toUtf8Bytes */.YW)(password, "NFKC"); + } + return (0,utils_data/* getBytesCopy */.Lm)(password); +} +function spelunk(object, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + (0,errors/* assertArgument */.MR)(match != null, "invalid path", "path", _path); + const path = match[1]; + const type = match[3]; + const reqd = (match[4] === "!"); + let cur = object; + for (const comp of path.toLowerCase().split('.')) { + // Search for a child object with a case-insensitive matching key + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { + break; + } + cur = cur[parseInt(comp)]; + } + else if (typeof (cur) === "object") { + let found = null; + for (const key in cur) { + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } + } + cur = found; + } + else { + cur = null; + } + if (cur == null) { + break; + } + } + (0,errors/* assertArgument */.MR)(!reqd || cur != null, "missing required value", "path", path); + if (type && cur != null) { + if (type === "int") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } + else if (Number.isSafeInteger(cur)) { + return cur; + } + } + if (type === "number") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); + } + } + if (type === "data") { + if (typeof (cur) === "string") { + return looseArrayify(cur); + } + } + if (type === "array" && Array.isArray(cur)) { + return cur; + } + if (type === typeof (cur)) { + return cur; + } + (0,errors/* assertArgument */.MR)(false, `wrong type found for ${type} `, "path", path); + } + return cur; +} +/* +export function follow(object: any, path: string): null | string { + let currentChild = object; + + for (const comp of path.toLowerCase().split('/')) { + + // Search for a child object with a case-insensitive matching key + let matchingChild = null; + for (const key in currentChild) { + if (key.toLowerCase() === comp) { + matchingChild = currentChild[key]; + break; + } + } + + if (matchingChild === null) { return null; } + + currentChild = matchingChild; + } + + return currentChild; +} + +// "path/to/something:type!" +export function followRequired(data: any, path: string): string { + const value = follow(data, path); + if (value != null) { return value; } + return logger.throwArgumentError("invalid value", `data:${ path }`, + JSON.stringify(data)); +} +*/ +// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) +/* +export function uuidV4(randomBytes: BytesLike): string { + const bytes = getBytes(randomBytes, "randomBytes"); + + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + const value = hexlify(bytes); + + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34), + ].join("-"); +} +*/ +//# sourceMappingURL=utils.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/_version.js +var _version = __webpack_require__(99529); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/json-keystore.js +/** + * The JSON Wallet formats allow a simple way to store the private + * keys needed in Ethereum along with related information and allows + * for extensible forms of encryption. + * + * These utilities facilitate decrypting and encrypting the most common + * JSON Wallet formats. + * + * @_subsection: api/wallet:JSON Wallets [json-wallets] + */ + + + + + + + +const defaultPath = "m/44'/60'/0'/0/0"; +/** + * Returns true if %%json%% is a valid JSON Keystore Wallet. + */ +function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version = ((data.version != null) ? parseInt(data.version) : 0); + if (version === 3) { + return true; + } + } + catch (error) { } + return false; +} +function decrypt(data, key, ciphertext) { + const cipher = spelunk(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = spelunk(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new CTR(key, iv); + return (0,utils_data/* hexlify */.c$)(aesCtr.decrypt(ciphertext)); + } + (0,errors/* assert */.vA)(false, "unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); +} +function getAccount(data, _key) { + const key = (0,utils_data/* getBytes */.q5)(_key); + const ciphertext = spelunk(data, "crypto.ciphertext:data!"); + const computedMAC = (0,utils_data/* hexlify */.c$)((0,keccak/* keccak256 */.S)((0,utils_data/* concat */.xW)([key.slice(16, 32), ciphertext]))).substring(2); + (0,errors/* assertArgument */.MR)(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]"); + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = (0,transaction_address/* computeAddress */.K)(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (!check.startsWith("0x")) { + check = "0x" + check; + } + (0,errors/* assertArgument */.MR)((0,address_address/* getAddress */.b)(check) === address, "keystore address/privateKey mismatch", "address", data.address); + } + const account = { address, privateKey }; + // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase + const version = spelunk(data, "x-ethers.version:string"); + if (version === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + account.mnemonic = { + path: (spelunk(data, "x-ethers.path:string") || defaultPath), + locale: (spelunk(data, "x-ethers.locale:string") || "en"), + entropy: (0,utils_data/* hexlify */.c$)((0,utils_data/* getBytes */.q5)(mnemonicAesCtr.decrypt(mnemonicCiphertext))) + }; + } + return account; +} +function getDecryptKdfParams(data) { + const kdf = spelunk(data, "crypto.kdf:string"); + if (kdf && typeof (kdf) === "string") { + if (kdf.toLowerCase() === "scrypt") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const N = spelunk(data, "crypto.kdfparams.n:int!"); + const r = spelunk(data, "crypto.kdfparams.r:int!"); + const p = spelunk(data, "crypto.kdfparams.p:int!"); + // Make sure N is a power of 2 + (0,errors/* assertArgument */.MR)(N > 0 && (N & (N - 1)) === 0, "invalid kdf.N", "kdf.N", N); + (0,errors/* assertArgument */.MR)(r > 0 && p > 0, "invalid kdf", "kdf", kdf); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + (0,errors/* assertArgument */.MR)(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen); + return { name: "scrypt", salt, N, r, p, dkLen: 64 }; + } + else if (kdf.toLowerCase() === "pbkdf2") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const prf = spelunk(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + (0,errors/* assertArgument */.MR)(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf); + const count = spelunk(data, "crypto.kdfparams.c:int!"); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + (0,errors/* assertArgument */.MR)(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen); + return { name: "pbkdf2", salt, count, dkLen, algorithm }; + } + } + (0,errors/* assertArgument */.MR)(false, "unsupported key-derivation function", "kdf", kdf); +} +/** + * Returns the account details for the JSON Keystore Wallet %%json%% + * using %%password%%. + * + * It is preferred to use the [async version](decryptKeystoreJson) + * instead, which allows a [[ProgressCallback]] to keep the user informed + * as to the decryption status. + * + * This method will block the event loop (freezing all UI) until decryption + * is complete, which can take quite some time, depending on the wallet + * paramters and platform. + */ +function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + const { salt, count, dkLen, algorithm } = params; + const key = (0,pbkdf2/* pbkdf2 */.A)(password, salt, count, dkLen, algorithm); + return getAccount(data, key); + } + (0,errors/* assert */.vA)(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); + const { salt, N, r, p, dkLen } = params; + const key = scryptSync(password, salt, N, r, p, dkLen); + return getAccount(data, key); +} +function json_keystore_stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +/** + * Resolves to the decrypted JSON Keystore Wallet %%json%% using the + * %%password%%. + * + * If provided, %%progress%% will be called periodically during the + * decrpytion to provide feedback, and if the function returns + * ``false`` will halt decryption. + * + * The %%progressCallback%% will **always** receive ``0`` before + * decryption begins and ``1`` when complete. + */ +async function decryptKeystoreJson(json, _password, progress) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + if (progress) { + progress(0); + await json_keystore_stall(0); + } + const { salt, count, dkLen, algorithm } = params; + const key = (0,pbkdf2/* pbkdf2 */.A)(password, salt, count, dkLen, algorithm); + if (progress) { + progress(1); + await json_keystore_stall(0); + } + return getAccount(data, key); + } + (0,errors/* assert */.vA)(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params }); + const { salt, N, r, p, dkLen } = params; + const key = await scrypt_scrypt(password, salt, N, r, p, dkLen, progress); + return getAccount(data, key); +} +function getEncryptKdfParams(options) { + // Check/generate the salt + const salt = (options.salt != null) ? (0,utils_data/* getBytes */.q5)(options.salt, "options.salt") : randomBytes(32); + // Override the scrypt password-based key derivation function parameters + let N = (1 << 17), r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; + } + if (options.scrypt.r) { + r = options.scrypt.r; + } + if (options.scrypt.p) { + p = options.scrypt.p; + } + } + (0,errors/* assertArgument */.MR)(typeof (N) === "number" && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N); + (0,errors/* assertArgument */.MR)(typeof (r) === "number" && r > 0 && Number.isSafeInteger(r), "invalid scrypt r parameter", "options.r", r); + (0,errors/* assertArgument */.MR)(typeof (p) === "number" && p > 0 && Number.isSafeInteger(p), "invalid scrypt p parameter", "options.p", p); + return { name: "scrypt", dkLen: 32, salt, N, r, p }; +} +function _encryptKeystore(key, kdf, account, options) { + const privateKey = (0,utils_data/* getBytes */.q5)(account.privateKey, "privateKey"); + // Override initialization vector + const iv = (options.iv != null) ? (0,utils_data/* getBytes */.q5)(options.iv, "options.iv") : randomBytes(16); + (0,errors/* assertArgument */.MR)(iv.length === 16, "invalid options.iv length", "options.iv", options.iv); + // Override the uuid + const uuidRandom = (options.uuid != null) ? (0,utils_data/* getBytes */.q5)(options.uuid, "options.uuid") : randomBytes(16); + (0,errors/* assertArgument */.MR)(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv); + // This will be used to encrypt the wallet (as per Web3 secret storage) + // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) + // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet) + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + // Encrypt the private key + const aesCtr = new CTR(derivedKey, iv); + const ciphertext = (0,utils_data/* getBytes */.q5)(aesCtr.encrypt(privateKey)); + // Compute the message authentication code, used to check the password + const mac = (0,keccak/* keccak256 */.S)((0,utils_data/* concat */.xW)([macPrefix, ciphertext])); + // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + const data = { + address: account.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: (0,utils_data/* hexlify */.c$)(iv).substring(2), + }, + ciphertext: (0,utils_data/* hexlify */.c$)(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: (0,utils_data/* hexlify */.c$)(kdf.salt).substring(2), + n: kdf.N, + dklen: 32, + p: kdf.p, + r: kdf.r + }, + mac: mac.substring(2) + } + }; + // If we have a mnemonic, encrypt it into the JSON wallet + if (account.mnemonic) { + const client = (options.client != null) ? options.client : `ethers/${_version/* version */.r}`; + const path = account.mnemonic.path || defaultPath; + const locale = account.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = (0,utils_data/* getBytes */.q5)(account.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = randomBytes(16); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = (0,utils_data/* getBytes */.q5)(mnemonicAesCtr.encrypt(entropy)); + const now = new Date(); + const timestamp = (now.getUTCFullYear() + "-" + + zpad(now.getUTCMonth() + 1, 2) + "-" + + zpad(now.getUTCDate(), 2) + "T" + + zpad(now.getUTCHours(), 2) + "-" + + zpad(now.getUTCMinutes(), 2) + "-" + + zpad(now.getUTCSeconds(), 2) + ".0Z"); + const gethFilename = ("UTC--" + timestamp + "--" + data.address); + data["x-ethers"] = { + client, gethFilename, path, locale, + mnemonicCounter: (0,utils_data/* hexlify */.c$)(mnemonicIv).substring(2), + mnemonicCiphertext: (0,utils_data/* hexlify */.c$)(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); +} +/** + * Return the JSON Keystore Wallet for %%account%% encrypted with + * %%password%%. + * + * The %%options%% can be used to tune the password-based key + * derivation function parameters, explicitly set the random values + * used. Any provided [[ProgressCallback]] is ignord. + */ +function encryptKeystoreJsonSync(account, password, options) { + if (options == null) { + options = {}; + } + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); + return _encryptKeystore((0,utils_data/* getBytes */.q5)(key), kdf, account, options); +} +/** + * Resolved to the JSON Keystore Wallet for %%account%% encrypted + * with %%password%%. + * + * The %%options%% can be used to tune the password-based key + * derivation function parameters, explicitly set the random values + * used and provide a [[ProgressCallback]] to receive periodic updates + * on the completion status.. + */ +async function encryptKeystoreJson(account, password, options) { + if (options == null) { + options = {}; + } + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = await scrypt_scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); + return _encryptKeystore((0,utils_data/* getBytes */.q5)(key), kdf, account, options); +} +//# sourceMappingURL=json-keystore.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/hdwallet.js +/** + * Explain HD Wallets.. + * + * @_subsection: api/wallet:HD Wallets [hd-wallets] + */ + + + + + + + + +/** + * The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``) + */ +const hdwallet_defaultPath = "m/44'/60'/0'/0/0"; +// "Bitcoin seed" +const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); +const HardenedBit = 0x80000000; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function hdwallet_zpad(value, length) { + let result = ""; + while (value) { + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); + } + while (result.length < length * 2) { + result = "0" + result; + } + return "0x" + result; +} +function encodeBase58Check(_value) { + const value = (0,utils_data/* getBytes */.q5)(_value); + const check = (0,utils_data/* dataSlice */.ZG)((0,sha2/* sha256 */.s)((0,sha2/* sha256 */.s)(value)), 0, 4); + const bytes = (0,utils_data/* concat */.xW)([value, check]); + return encodeBase58(bytes); +} +const _guard = {}; +function ser_I(index, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index & HardenedBit) { + (0,errors/* assert */.vA)(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" + }); + // Data = 0x00 || ser_256(k_par) + data.set((0,utils_data/* getBytes */.q5)(privateKey), 1); + } + else { + // Data = ser_p(point(k_par)) + data.set((0,utils_data/* getBytes */.q5)(publicKey)); + } + // Data += ser_32(i) + for (let i = 24; i >= 0; i -= 8) { + data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); + } + const I = (0,utils_data/* getBytes */.q5)(computeHmac("sha512", chainCode, data)); + return { IL: I.slice(0, 32), IR: I.slice(32) }; +} +function derivePath(node, path) { + const components = path.split("/"); + (0,errors/* assertArgument */.MR)(components.length > 0, "invalid path", "path", path); + if (components[0] === "m") { + (0,errors/* assertArgument */.MR)(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${node.depth}`, "path", path); + components.shift(); + } + let result = node; + for (let i = 0; i < components.length; i++) { + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + (0,errors/* assertArgument */.MR)(index < HardenedBit, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(HardenedBit + index); + } + else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + (0,errors/* assertArgument */.MR)(index < HardenedBit, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(index); + } + else { + (0,errors/* assertArgument */.MR)(false, "invalid path component", `path[${i}]`, component); + } + } + return result; +} +/** + * An **HDNodeWallet** is a [[Signer]] backed by the private key derived + * from an HD Node using the [[link-bip-32]] stantard. + * + * An HD Node forms a hierarchal structure with each HD Node having a + * private key and the ability to derive child HD Nodes, defined by + * a path indicating the index of each child. + */ +class HDNodeWallet extends BaseWallet { + /** + * The compressed public key. + */ + publicKey; + /** + * The fingerprint. + * + * A fingerprint allows quick qay to detect parent and child nodes, + * but developers should be prepared to deal with collisions as it + * is only 4 bytes. + */ + fingerprint; + /** + * The parent fingerprint. + */ + parentFingerprint; + /** + * The mnemonic used to create this HD Node, if available. + * + * Sources such as extended keys do not encode the mnemonic, in + * which case this will be ``null``. + */ + mnemonic; + /** + * The chaincode, which is effectively a public key used + * to derive children. + */ + chainCode; + /** + * The derivation path of this wallet. + * + * Since extended keys do not provider full path details, this + * may be ``null``, if instantiated from a source that does not + * enocde it. + */ + path; + /** + * The child index of this wallet. Values over ``2 *\* 31`` indicate + * the node is hardened. + */ + index; + /** + * The depth of this wallet, which is the number of components + * in its path. + */ + depth; + /** + * @private + */ + constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { + super(signingKey, provider); + (0,errors/* assertPrivate */.gk)(guard, _guard, "HDNodeWallet"); + (0,properties/* defineProperties */.n)(this, { publicKey: signingKey.compressedPublicKey }); + const fingerprint = (0,utils_data/* dataSlice */.ZG)(ripemd160_ripemd160((0,sha2/* sha256 */.s)(this.publicKey)), 0, 4); + (0,properties/* defineProperties */.n)(this, { + parentFingerprint, fingerprint, + chainCode, path, index, depth + }); + (0,properties/* defineProperties */.n)(this, { mnemonic }); + } + connect(provider) { + return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); + } + #account() { + const account = { address: this.address, privateKey: this.privateKey }; + const m = this.mnemonic; + if (this.path && m && m.wordlist.locale === "en" && m.password === "") { + account.mnemonic = { + path: this.path, + locale: "en", + entropy: m.entropy + }; + } + return account; + } + /** + * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with + * %%password%%. + * + * If %%progressCallback%% is specified, it will receive periodic + * updates as the encryption process progreses. + */ + async encrypt(password, progressCallback) { + return await encryptKeystoreJson(this.#account(), password, { progressCallback }); + } + /** + * Returns a [JSON Keystore Wallet](json-wallets) encryped with + * %%password%%. + * + * It is preferred to use the [async version](encrypt) instead, + * which allows a [[ProgressCallback]] to keep the user informed. + * + * This method will block the event loop (freezing all UI) until + * it is complete, which may be a non-trivial duration. + */ + encryptSync(password) { + return encryptKeystoreJsonSync(this.#account(), password); + } + /** + * The extended key. + * + * This key will begin with the prefix ``xpriv`` and can be used to + * reconstruct this HD Node to derive its children. + */ + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + (0,errors/* assert */.vA)(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); + return encodeBase58Check((0,utils_data/* concat */.xW)([ + "0x0488ADE4", hdwallet_zpad(this.depth, 1), this.parentFingerprint, + hdwallet_zpad(this.index, 4), this.chainCode, + (0,utils_data/* concat */.xW)(["0x00", this.privateKey]) + ])); + } + /** + * Returns true if this wallet has a path, providing a Type Guard + * that the path is non-null. + */ + hasPath() { return (this.path != null); } + /** + * Returns a neutered HD Node, which removes the private details + * of an HD Node. + * + * A neutered node has no private key, but can be used to derive + * child addresses and other public data about the HD Node. + */ + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + } + /** + * Return the child for %%index%%. + */ + deriveChild(_index) { + const index = (0,maths/* getNumber */.WZ)(_index, "index"); + (0,errors/* assertArgument */.MR)(index <= 0xffffffff, "invalid index", "index", index); + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); + const ki = new signing_key/* SigningKey */.h((0,maths/* toBeHex */.up)(((0,maths/* toBigInt */.Dg)(IL) + BigInt(this.privateKey)) % N, 32)); + return new HDNodeWallet(_guard, ki, this.fingerprint, (0,utils_data/* hexlify */.c$)(IR), path, index, this.depth + 1, this.mnemonic, this.provider); + } + /** + * Return the HDNode for %%path%% from this node. + */ + derivePath(path) { + return derivePath(this, path); + } + static #fromSeed(_seed, mnemonic) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isBytesLike */.f)(_seed), "invalid seed", "seed", "[REDACTED]"); + const seed = (0,utils_data/* getBytes */.q5)(_seed, "seed"); + (0,errors/* assertArgument */.MR)(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]"); + const I = (0,utils_data/* getBytes */.q5)(computeHmac("sha512", MasterSecret, seed)); + const signingKey = new signing_key/* SigningKey */.h((0,utils_data/* hexlify */.c$)(I.slice(0, 32))); + return new HDNodeWallet(_guard, signingKey, "0x00000000", (0,utils_data/* hexlify */.c$)(I.slice(32)), "m", 0, 0, mnemonic, null); + } + /** + * Creates a new HD Node from %%extendedKey%%. + * + * If the %%extendedKey%% will either have a prefix or ``xpub`` or + * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]]) + * or full HD Node ([[HDNodeWallet) respectively. + */ + static fromExtendedKey(extendedKey) { + const bytes = (0,maths/* toBeArray */.c4)(decodeBase58(extendedKey)); // @TODO: redact + (0,errors/* assertArgument */.MR)(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]"); + const depth = bytes[4]; + const parentFingerprint = (0,utils_data/* hexlify */.c$)(bytes.slice(5, 9)); + const index = parseInt((0,utils_data/* hexlify */.c$)(bytes.slice(9, 13)).substring(2), 16); + const chainCode = (0,utils_data/* hexlify */.c$)(bytes.slice(13, 45)); + const key = bytes.slice(45, 78); + switch ((0,utils_data/* hexlify */.c$)(bytes.slice(0, 4))) { + // Public Key + case "0x0488b21e": + case "0x043587cf": { + const publicKey = (0,utils_data/* hexlify */.c$)(key); + return new HDNodeVoidWallet(_guard, (0,transaction_address/* computeAddress */.K)(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); + } + // Private Key + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNodeWallet(_guard, new signing_key/* SigningKey */.h(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); + } + (0,errors/* assertArgument */.MR)(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]"); + } + /** + * Creates a new random HDNode. + */ + static createRandom(password, path, wordlist) { + if (password == null) { + password = ""; + } + if (path == null) { + path = hdwallet_defaultPath; + } + if (wordlist == null) { + wordlist = lang_en/* LangEn */.U.wordlist(); + } + const mnemonic = wallet_mnemonic/* Mnemonic */.v.fromEntropy(randomBytes(16), password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + /** + * Create an HD Node from %%mnemonic%%. + */ + static fromMnemonic(mnemonic, path) { + if (!path) { + path = hdwallet_defaultPath; + } + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + /** + * Creates an HD Node from a mnemonic %%phrase%%. + */ + static fromPhrase(phrase, password, path, wordlist) { + if (password == null) { + password = ""; + } + if (path == null) { + path = hdwallet_defaultPath; + } + if (wordlist == null) { + wordlist = lang_en/* LangEn */.U.wordlist(); + } + const mnemonic = wallet_mnemonic/* Mnemonic */.v.fromPhrase(phrase, password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + /** + * Creates an HD Node from a %%seed%%. + */ + static fromSeed(seed) { + return HDNodeWallet.#fromSeed(seed, null); + } +} +/** + * A **HDNodeVoidWallet** cannot sign, but provides access to + * the children nodes of a [[link-bip-32]] HD wallet addresses. + * + * The can be created by using an extended ``xpub`` key to + * [[HDNodeWallet_fromExtendedKey]] or by + * [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]]. + */ +class HDNodeVoidWallet extends VoidSigner { + /** + * The compressed public key. + */ + publicKey; + /** + * The fingerprint. + * + * A fingerprint allows quick qay to detect parent and child nodes, + * but developers should be prepared to deal with collisions as it + * is only 4 bytes. + */ + fingerprint; + /** + * The parent node fingerprint. + */ + parentFingerprint; + /** + * The chaincode, which is effectively a public key used + * to derive children. + */ + chainCode; + /** + * The derivation path of this wallet. + * + * Since extended keys do not provider full path details, this + * may be ``null``, if instantiated from a source that does not + * enocde it. + */ + path; + /** + * The child index of this wallet. Values over ``2 *\* 31`` indicate + * the node is hardened. + */ + index; + /** + * The depth of this wallet, which is the number of components + * in its path. + */ + depth; + /** + * @private + */ + constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { + super(address, provider); + (0,errors/* assertPrivate */.gk)(guard, _guard, "HDNodeVoidWallet"); + (0,properties/* defineProperties */.n)(this, { publicKey }); + const fingerprint = (0,utils_data/* dataSlice */.ZG)(ripemd160_ripemd160((0,sha2/* sha256 */.s)(publicKey)), 0, 4); + (0,properties/* defineProperties */.n)(this, { + publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth + }); + } + connect(provider) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); + } + /** + * The extended key. + * + * This key will begin with the prefix ``xpub`` and can be used to + * reconstruct this neutered key to derive its children addresses. + */ + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + (0,errors/* assert */.vA)(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" }); + return encodeBase58Check((0,utils_data/* concat */.xW)([ + "0x0488B21E", + hdwallet_zpad(this.depth, 1), + this.parentFingerprint, + hdwallet_zpad(this.index, 4), + this.chainCode, + this.publicKey, + ])); + } + /** + * Returns true if this wallet has a path, providing a Type Guard + * that the path is non-null. + */ + hasPath() { return (this.path != null); } + /** + * Return the child for %%index%%. + */ + deriveChild(_index) { + const index = (0,maths/* getNumber */.WZ)(_index, "index"); + (0,errors/* assertArgument */.MR)(index <= 0xffffffff, "invalid index", "index", index); + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); + const Ki = signing_key/* SigningKey */.h.addPoints(IL, this.publicKey, true); + const address = (0,transaction_address/* computeAddress */.K)(Ki); + return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, (0,utils_data/* hexlify */.c$)(IR), path, index, this.depth + 1, this.provider); + } + /** + * Return the signer for %%path%% from this node. + */ + derivePath(path) { + return derivePath(this, path); + } +} +/* +export class HDNodeWalletManager { + #root: HDNodeWallet; + + constructor(phrase: string, password?: null | string, path?: null | string, locale?: null | Wordlist) { + if (password == null) { password = ""; } + if (path == null) { path = "m/44'/60'/0'/0"; } + if (locale == null) { locale = LangEn.wordlist(); } + this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale); + } + + getSigner(index?: number): HDNodeWallet { + return this.#root.deriveChild((index == null) ? 0: index); + } +} +*/ +/** + * Returns the [[link-bip-32]] path for the account at %%index%%. + * + * This is the pattern used by wallets like Ledger. + * + * There is also an [alternate pattern](getIndexedAccountPath) used by + * some software. + */ +function getAccountPath(_index) { + const index = getNumber(_index, "index"); + assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index); + return `m/44'/60'/${index}'/0/0`; +} +/** + * Returns the path using an alternative pattern for deriving accounts, + * at %%index%%. + * + * This derivation path uses the //index// component rather than the + * //account// component to derive sequential accounts. + * + * This is the pattern used by wallets like MetaMask. + */ +function getIndexedAccountPath(_index) { + const index = getNumber(_index, "index"); + assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index); + return `m/44'/60'/0'/0/${index}`; +} +//# sourceMappingURL=hdwallet.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/json-crowdsale.js +/** + * @_subsection: api/wallet:JSON Wallets [json-wallets] + */ + + + + + + +/** + * Returns true if %%json%% is a valid JSON Crowdsale wallet. + */ +function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } + catch (error) { } + return false; +} +// See: https://github.com/ethereum/pyethsaletool +/** + * Before Ethereum launched, it was necessary to create a wallet + * format for backers to use, which would be used to receive ether + * as a reward for contributing to the project. + * + * The [[link-crowdsale]] format is now obsolete, but it is still + * useful to support and the additional code is fairly trivial as + * all the primitives required are used through core portions of + * the library. + */ +function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + // Ethereum Address + const address = (0,address_address/* getAddress */.b)(spelunk(data, "ethaddr:string!")); + // Encrypted Seed + const encseed = looseArrayify(spelunk(data, "encseed:string!")); + (0,errors/* assertArgument */.MR)(encseed && (encseed.length % 16) === 0, "invalid encseed", "json", json); + const key = (0,utils_data/* getBytes */.q5)((0,pbkdf2/* pbkdf2 */.A)(password, password, 2000, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + // Decrypt the seed + const aesCbc = new CBC(key, iv); + const seed = pkcs7Strip((0,utils_data/* getBytes */.q5)(aesCbc.decrypt(encryptedSeed))); + // This wallet format is weird... Convert the binary encoded hex to a string. + let seedHex = ""; + for (let i = 0; i < seed.length; i++) { + seedHex += String.fromCharCode(seed[i]); + } + return { address, privateKey: (0,id.id)(seedHex) }; +} +//# sourceMappingURL=json-crowdsale.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wallet/wallet.js +/* provided dependency */ var wallet_console = __webpack_require__(96763); + + + + + + + +function wallet_stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +/** + * A **Wallet** manages a single private key which is used to sign + * transactions, messages and other common payloads. + * + * This class is generally the main entry point for developers + * that wish to use a private key directly, as it can create + * instances from a large variety of common sources, including + * raw private key, [[link-bip-39]] mnemonics and encrypte JSON + * wallets. + */ +class Wallet extends BaseWallet { + /** + * Create a new wallet for the private %%key%%, optionally connected + * to %%provider%%. + */ + constructor(key, provider) { + if (typeof (key) === "string" && !key.startsWith("0x")) { + key = "0x" + key; + } + let signingKey = (typeof (key) === "string") ? new signing_key/* SigningKey */.h(key) : key; + super(signingKey, provider); + } + connect(provider) { + return new Wallet(this.signingKey, provider); + } + /** + * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with + * %%password%%. + * + * If %%progressCallback%% is specified, it will receive periodic + * updates as the encryption process progreses. + */ + async encrypt(password, progressCallback) { + const account = { address: this.address, privateKey: this.privateKey }; + return await encryptKeystoreJson(account, password, { progressCallback }); + } + /** + * Returns a [JSON Keystore Wallet](json-wallets) encryped with + * %%password%%. + * + * It is preferred to use the [async version](encrypt) instead, + * which allows a [[ProgressCallback]] to keep the user informed. + * + * This method will block the event loop (freezing all UI) until + * it is complete, which may be a non-trivial duration. + */ + encryptSync(password) { + const account = { address: this.address, privateKey: this.privateKey }; + return encryptKeystoreJsonSync(account, password); + } + static #fromAccount(account) { + (0,errors/* assertArgument */.MR)(account, "invalid JSON wallet", "json", "[ REDACTED ]"); + if ("mnemonic" in account && account.mnemonic && account.mnemonic.locale === "en") { + const mnemonic = wallet_mnemonic/* Mnemonic */.v.fromEntropy(account.mnemonic.entropy); + const wallet = HDNodeWallet.fromMnemonic(mnemonic, account.mnemonic.path); + if (wallet.address === account.address && wallet.privateKey === account.privateKey) { + return wallet; + } + wallet_console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); + } + const wallet = new Wallet(account.privateKey); + (0,errors/* assertArgument */.MR)(wallet.address === account.address, "address/privateKey mismatch", "json", "[ REDACTED ]"); + return wallet; + } + /** + * Creates (asynchronously) a **Wallet** by decrypting the %%json%% + * with %%password%%. + * + * If %%progress%% is provided, it is called periodically during + * decryption so that any UI can be updated. + */ + static async fromEncryptedJson(json, password, progress) { + let account = null; + if (isKeystoreJson(json)) { + account = await decryptKeystoreJson(json, password, progress); + } + else if (isCrowdsaleJson(json)) { + if (progress) { + progress(0); + await wallet_stall(0); + } + account = decryptCrowdsaleJson(json, password); + if (progress) { + progress(1); + await wallet_stall(0); + } + } + return Wallet.#fromAccount(account); + } + /** + * Creates a **Wallet** by decrypting the %%json%% with %%password%%. + * + * The [[fromEncryptedJson]] method is preferred, as this method + * will lock up and freeze the UI during decryption, which may take + * some time. + */ + static fromEncryptedJsonSync(json, password) { + let account = null; + if (isKeystoreJson(json)) { + account = decryptKeystoreJsonSync(json, password); + } + else if (isCrowdsaleJson(json)) { + account = decryptCrowdsaleJson(json, password); + } + else { + (0,errors/* assertArgument */.MR)(false, "invalid JSON wallet", "json", "[ REDACTED ]"); + } + return Wallet.#fromAccount(account); + } + /** + * Creates a new random [[HDNodeWallet]] using the available + * [cryptographic random source](randomBytes). + * + * If there is no crytographic random source, this will throw. + */ + static createRandom(provider) { + const wallet = HDNodeWallet.createRandom(); + if (provider) { + return wallet.connect(provider); + } + return wallet; + } + /** + * Creates a [[HDNodeWallet]] for %%phrase%%. + */ + static fromPhrase(phrase, provider) { + const wallet = HDNodeWallet.fromPhrase(phrase); + if (provider) { + return wallet.connect(provider); + } + return wallet; + } +} +//# sourceMappingURL=wallet.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/providers/provider-browser.js + + +; +/** + * A **BrowserProvider** is intended to wrap an injected provider which + * adheres to the [[link-eip-1193]] standard, which most (if not all) + * currently do. + */ +class BrowserProvider extends JsonRpcApiPollingProvider { + #request; + /** + * Connnect to the %%ethereum%% provider, optionally forcing the + * %%network%%. + */ + constructor(ethereum, network) { + (0,errors/* assertArgument */.MR)(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum); + super(network, { batchMaxCount: 1 }); + this.#request = async (method, params) => { + const payload = { method, params }; + this.emit("debug", { action: "sendEip1193Request", payload }); + try { + const result = await ethereum.request(payload); + this.emit("debug", { action: "receiveEip1193Result", result }); + return result; + } + catch (e) { + const error = new Error(e.message); + error.code = e.code; + error.data = e.data; + error.payload = payload; + this.emit("debug", { action: "receiveEip1193Error", error }); + throw error; + } + }; + } + async send(method, params) { + await this._start(); + return await super.send(method, params); + } + async _send(payload) { + (0,errors/* assertArgument */.MR)(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload); + try { + const result = await this.#request(payload.method, payload.params || []); + return [{ id: payload.id, result }]; + } + catch (e) { + return [{ + id: payload.id, + error: { code: e.code, data: e.data, message: e.message } + }]; + } + } + getRpcError(payload, error) { + error = JSON.parse(JSON.stringify(error)); + // EIP-1193 gives us some machine-readable error codes, so rewrite + // them into + switch (error.error.code || -1) { + case 4001: + error.error.message = `ethers-user-denied: ${error.error.message}`; + break; + case 4200: + error.error.message = `ethers-unsupported: ${error.error.message}`; + break; + } + return super.getRpcError(payload, error); + } + /** + * Resolves to ``true`` if the provider manages the %%address%%. + */ + async hasSigner(address) { + if (address == null) { + address = 0; + } + const accounts = await this.send("eth_accounts", []); + if (typeof (address) === "number") { + return (accounts.length > address); + } + address = address.toLowerCase(); + return accounts.filter((a) => (a.toLowerCase() === address)).length !== 0; + } + async getSigner(address) { + if (address == null) { + address = 0; + } + if (!(await this.hasSigner(address))) { + try { + //const resp = + await this.#request("eth_requestAccounts", []); + //console.log("RESP", resp); + } + catch (error) { + const payload = error.payload; + throw this.getRpcError(payload, { id: payload.id, error }); + } + } + return await super.getSigner(address); + } +} +//# sourceMappingURL=provider-browser.js.map +// EXTERNAL MODULE: ./src/typechain/index.ts + 8 modules +var typechain = __webpack_require__(67276); +// EXTERNAL MODULE: ./src/utils.ts +var src_utils = __webpack_require__(67418); +// EXTERNAL MODULE: ./src/multicall.ts +var multicall = __webpack_require__(48486); +;// CONCATENATED MODULE: ./src/providers.ts +/* provided dependency */ var providers_console = __webpack_require__(96763); + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + + + + + +const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +const providers_fetch = (browser_ponyfill_default()); +function getHttpAgent({ + fetchUrl, + proxyUrl, + torPort, + retry +}) { + if (torPort) { + return new socks_proxy_agent_ignored_.SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`); + } + if (!proxyUrl) { + return; + } + const isHttps = fetchUrl.includes("https://"); + if (proxyUrl.includes("socks://") || proxyUrl.includes("socks4://") || proxyUrl.includes("socks5://")) { + return new socks_proxy_agent_ignored_.SocksProxyAgent(proxyUrl); + } + if (proxyUrl.includes("http://") || proxyUrl.includes("https://")) { + if (isHttps) { + return new https_proxy_agent_ignored_.HttpsProxyAgent(proxyUrl); + } + return new http_proxy_agent_ignored_.HttpProxyAgent(proxyUrl); + } +} +function fetchData(_0) { + return __async(this, arguments, function* (url, options = {}) { + var _a, _b, _c; + const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; + const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; + const userAgent = (_c = options.userAgent) != null ? _c : defaultUserAgent; + let retry = 0; + let errorObject; + if (!options.method) { + if (!options.body) { + options.method = "GET"; + } else { + options.method = "POST"; + } + } + if (!options.headers) { + options.headers = {}; + } + if (src_utils/* isNode */.Ll && !options.headers["User-Agent"]) { + options.headers["User-Agent"] = userAgent; + } + while (retry < MAX_RETRY + 1) { + let timeout; + if (!options.signal && options.timeout) { + const controller = new AbortController(); + options.signal = controller.signal; + timeout = setTimeout(() => { + controller.abort(); + }, options.timeout); + } + if (!options.agent && src_utils/* isNode */.Ll && (options.proxy || options.torPort)) { + options.agent = getHttpAgent({ + fetchUrl: url, + proxyUrl: options.proxy, + torPort: options.torPort, + retry + }); + } + if (options.debug && typeof options.debug === "function") { + options.debug("request", { + url, + retry, + errorObject, + options + }); + } + try { + const resp = yield providers_fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + redirect: options.redirect, + signal: options.signal, + agent: options.agent + }); + if (options.debug && typeof options.debug === "function") { + options.debug("response", resp); + } + if (!resp.ok) { + const errMsg = `Request to ${url} failed with error code ${resp.status}: +` + (yield resp.text()); + throw new Error(errMsg); + } + if (options.returnResponse) { + return resp; + } + const contentType = resp.headers.get("content-type"); + if (contentType == null ? void 0 : contentType.includes("application/json")) { + return yield resp.json(); + } + if (contentType == null ? void 0 : contentType.includes("text")) { + return yield resp.text(); + } + return resp; + } catch (error) { + if (timeout) { + clearTimeout(timeout); + } + errorObject = error; + retry++; + yield (0,src_utils/* sleep */.yy)(RETRY_ON); + } finally { + if (timeout) { + clearTimeout(timeout); + } + } + } + if (options.debug && typeof options.debug === "function") { + options.debug("error", errorObject); + } + throw errorObject; + }); +} +const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async(void 0, null, function* () { + let signal; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { + controller.abort(); + }); + } + const init = __spreadProps(__spreadValues({}, options), { + method: req.method || "POST", + headers: req.headers, + body: req.body || void 0, + signal, + returnResponse: true + }); + const resp = yield fetchData(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = yield resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, + body + }; +}); +const oracleMapper = /* @__PURE__ */ new Map(); +const multicallMapper = /* @__PURE__ */ new Map(); +function getGasOraclePlugin(networkKey, fetchOptions) { + const gasStationApi = (fetchOptions == null ? void 0 : fetchOptions.gasStationApi) || "https://gasstation.polygon.technology/v2"; + return new FetchUrlFeeDataNetworkPlugin(gasStationApi, (fetchFeeData, provider, request) => __async(this, null, function* () { + if (!oracleMapper.has(networkKey)) { + oracleMapper.set(networkKey, typechain/* GasPriceOracle__factory */.Hu.connect(fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle, provider)); + } + if (!multicallMapper.has(networkKey)) { + multicallMapper.set( + networkKey, + typechain/* Multicall__factory */.Q2.connect("0xcA11bde05977b3631167028862bE2a173976CA11", provider) + ); + } + const Oracle = oracleMapper.get(networkKey); + const Multicall2 = multicallMapper.get(networkKey); + const [timestamp, heartbeat, feePerGas, priorityFeePerGas] = yield (0,multicall/* multicall */.C)(Multicall2, [ + { + contract: Oracle, + name: "timestamp" + }, + { + contract: Oracle, + name: "heartbeat" + }, + { + contract: Oracle, + name: "maxFeePerGas" + }, + { + contract: Oracle, + name: "maxPriorityFeePerGas" + } + ]); + const isOutdated = Number(timestamp) <= Date.now() / 1e3 - Number(heartbeat); + if (!isOutdated) { + const maxPriorityFeePerGas = priorityFeePerGas * BigInt(13) / BigInt(10); + const maxFeePerGas = feePerGas * BigInt(2) + maxPriorityFeePerGas; + return { + gasPrice: maxFeePerGas, + maxFeePerGas, + maxPriorityFeePerGas + }; + } + const fetchReq = new FetchRequest(gasStationApi); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + if (src_utils/* isNode */.Ll) { + fetchReq.setHeader("User-Agent", "ethers"); + } + const [ + { + bodyJson: { fast } + }, + { gasPrice } + ] = yield Promise.all([fetchReq.send(), fetchFeeData()]); + return { + gasPrice, + maxFeePerGas: (0,units/* parseUnits */.XS)(`${fast.maxFee}`, 9), + maxPriorityFeePerGas: (0,units/* parseUnits */.XS)(`${fast.maxPriorityFee}`, 9) + }; + })); +} +function getProvider(rpcUrl, fetchOptions) { + return __async(this, null, function* () { + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const _staticNetwork = yield new JsonRpcProvider(fetchReq).getNetwork(); + const ensPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.Ens"); + const gasCostPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.GasCost"); + const gasStationPlugin = _staticNetwork.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + const staticNetwork = new Network(_staticNetwork.name, _staticNetwork.chainId); + if (ensPlugin) { + staticNetwork.attachPlugin(ensPlugin); + } + if (gasCostPlugin) { + staticNetwork.attachPlugin(gasCostPlugin); + } + if (fetchOptions == null ? void 0 : fetchOptions.gasPriceOracle) { + staticNetwork.attachPlugin(getGasOraclePlugin(`${_staticNetwork.chainId}_${rpcUrl}`, fetchOptions)); + } else if (gasStationPlugin) { + staticNetwork.attachPlugin(gasStationPlugin); + } + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || 1e3; + return provider; + }); +} +function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) { + const { networkName, reverseRecordsContract, gasPriceOracleContract, gasStationApi, pollInterval } = config; + const hasEns = Boolean(reverseRecordsContract); + const fetchReq = new FetchRequest(rpcUrl); + fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); + const staticNetwork = new Network(networkName, netId); + if (hasEns) { + staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId))); + } + staticNetwork.attachPlugin(new GasCostPlugin()); + if (gasPriceOracleContract) { + staticNetwork.attachPlugin( + getGasOraclePlugin(`${netId}_${rpcUrl}`, { + gasPriceOracle: gasPriceOracleContract, + gasStationApi + }) + ); + } + const provider = new JsonRpcProvider(fetchReq, staticNetwork, { + staticNetwork + }); + provider.pollingInterval = (fetchOptions == null ? void 0 : fetchOptions.pollingInterval) || pollInterval * 1e3; + return provider; +} +const populateTransaction = (signer, tx) => __async(void 0, null, function* () { + const provider = signer.provider; + if (!tx.from) { + tx.from = signer.address; + } else if (tx.from !== signer.address) { + const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`; + throw new Error(errMsg); + } + const [feeData, nonce] = yield Promise.all([ + (() => __async(void 0, null, function* () { + if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + return new providers_provider/* FeeData */.J9(null, BigInt(tx.maxFeePerGas), BigInt(tx.maxPriorityFeePerGas)); + } + if (tx.gasPrice) { + return new providers_provider/* FeeData */.J9(BigInt(tx.gasPrice), null, null); + } + const fetchedFeeData = yield provider.getFeeData(); + if (fetchedFeeData.maxFeePerGas && fetchedFeeData.maxPriorityFeePerGas) { + return new providers_provider/* FeeData */.J9( + null, + fetchedFeeData.maxFeePerGas * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + fetchedFeeData.maxPriorityFeePerGas + ); + } else { + return new providers_provider/* FeeData */.J9( + fetchedFeeData.gasPrice * (BigInt(1e4) + BigInt(signer.gasPriceBump)) / BigInt(1e4), + null, + null + ); + } + }))(), + (() => __async(void 0, null, function* () { + if (tx.nonce) { + return tx.nonce; + } + let fetchedNonce = yield provider.getTransactionCount(signer.address, "pending"); + if (signer.bumpNonce && signer.nonce && signer.nonce >= fetchedNonce) { + providers_console.log( + `populateTransaction: bumping nonce from ${fetchedNonce} to ${fetchedNonce + 1} for ${signer.address}` + ); + fetchedNonce++; + } + return fetchedNonce; + }))() + ]); + tx.nonce = nonce; + if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) { + tx.maxFeePerGas = feeData.maxFeePerGas; + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + if (!tx.type) { + tx.type = 2; + } + delete tx.gasPrice; + } else if (feeData.gasPrice) { + tx.gasPrice = feeData.gasPrice; + if (!tx.type) { + tx.type = 0; + } + delete tx.maxFeePerGas; + delete tx.maxPriorityFeePerGas; + } + tx.gasLimit = tx.gasLimit || (yield (() => __async(void 0, null, function* () { + try { + const gasLimit = yield provider.estimateGas(tx); + return gasLimit === BigInt(21e3) ? gasLimit : gasLimit * (BigInt(1e4) + BigInt(signer.gasLimitBump)) / BigInt(1e4); + } catch (err) { + if (signer.gasFailover) { + providers_console.log("populateTransaction: warning gas estimation failed falling back to 3M gas"); + return BigInt("3000000"); + } + throw err; + } + }))()); + return tx; +}); +class TornadoWallet extends Wallet { + constructor(key, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(key, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + static fromMnemonic(mneomnic, provider, index = 0, options) { + const defaultPath = `m/44'/60'/0'/0/${index}`; + const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, void 0, defaultPath); + return new TornadoWallet(privateKey, provider, options); + } + populateTransaction(tx) { + return __async(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoVoidSigner extends VoidSigner { + constructor(address, provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(address, provider); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + populateTransaction(tx) { + return __async(this, null, function* () { + const txObject = yield populateTransaction(this, tx); + this.nonce = txObject.nonce; + return __superGet(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); + }); + } +} +class TornadoRpcSigner extends JsonRpcSigner { + constructor(provider, address, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce } = {}) { + super(provider, address); + this.gasPriceBump = gasPriceBump != null ? gasPriceBump : 1e3; + this.gasLimitBump = gasLimitBump != null ? gasLimitBump : 3e3; + this.gasFailover = gasFailover != null ? gasFailover : false; + this.bumpNonce = bumpNonce != null ? bumpNonce : false; + } + sendUncheckedTransaction(tx) { + return __async(this, null, function* () { + return __superGet(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); + }); + } +} +class TornadoBrowserProvider extends BrowserProvider { + constructor(ethereum, network, options) { + super(ethereum, network); + this.options = options; + } + getSigner(address) { + return __async(this, null, function* () { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const signerAddress = (yield __superGet(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; + if (((_a = this.options) == null ? void 0 : _a.webChainId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet(TornadoBrowserProvider.prototype, this, "send").call(this, "eth_chainId", [])) !== Number((_c = this.options) == null ? void 0 : _c.webChainId)) { + yield this.options.connectWallet(); + } + if ((_d = this.options) == null ? void 0 : _d.handleNetworkChanges) { + (_e = window == null ? void 0 : window.ethereum) == null ? void 0 : _e.on("chainChanged", this.options.handleNetworkChanges); + } + if ((_f = this.options) == null ? void 0 : _f.handleAccountChanges) { + (_g = window == null ? void 0 : window.ethereum) == null ? void 0 : _g.on("accountsChanged", this.options.handleAccountChanges); + } + if ((_h = this.options) == null ? void 0 : _h.handleAccountDisconnect) { + (_i = window == null ? void 0 : window.ethereum) == null ? void 0 : _i.on("disconnect", this.options.handleAccountDisconnect); + } + return new TornadoRpcSigner(this, signerAddress, this.options); + }); + } +} + + +/***/ }), + +/***/ 57194: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ OR: () => (/* binding */ RelayerClient), +/* harmony export */ XF: () => (/* binding */ getSupportedInstances), +/* harmony export */ c$: () => (/* binding */ getWeightRandom), +/* harmony export */ mU: () => (/* binding */ isRelayerUpdated), +/* harmony export */ pO: () => (/* binding */ MIN_STAKE_BALANCE), +/* harmony export */ qo: () => (/* binding */ parseSemanticVersion), +/* harmony export */ sN: () => (/* binding */ pickWeightedRandomRelayer), +/* harmony export */ zy: () => (/* binding */ calculateScore) +/* harmony export */ }); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(99770); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30031); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(64563); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67418); +/* harmony import */ var _networkConfig__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(59499); +/* harmony import */ var _providers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(64819); +/* harmony import */ var _schemas__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7613); +/* provided dependency */ var console = __webpack_require__(96763); + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + + +const MIN_STAKE_BALANCE = (0,ethers__WEBPACK_IMPORTED_MODULE_4__/* .parseEther */ .g5)("500"); +const semVerRegex = new RegExp("^(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)\\.(?0|[1-9]\\d*)(?:-(?(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); +function parseSemanticVersion(version) { + const { groups } = semVerRegex.exec(version); + return groups; +} +function isRelayerUpdated(relayerVersion, netId) { + const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); + const requiredMajor = netId === _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET ? "4" : "5"; + const isUpdatedMajor = major === requiredMajor; + if (prerelease) + return false; + return isUpdatedMajor && (Number(patch) >= 5 || netId !== _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET); +} +function calculateScore({ stakeBalance, tornadoServiceFee }, minFee = 0.33, maxFee = 0.53) { + if (tornadoServiceFee < minFee) { + tornadoServiceFee = minFee; + } else if (tornadoServiceFee >= maxFee) { + return BigInt(0); + } + const serviceFeeCoefficient = (tornadoServiceFee - minFee) ** 2; + const feeDiffCoefficient = 1 / (maxFee - minFee) ** 2; + const coefficientsMultiplier = 1 - feeDiffCoefficient * serviceFeeCoefficient; + return BigInt(Math.floor(Number(stakeBalance) * coefficientsMultiplier)); +} +function getWeightRandom(weightsScores, random) { + for (let i = 0; i < weightsScores.length; i++) { + if (random < weightsScores[i]) { + return i; + } + random = random - weightsScores[i]; + } + return Math.floor(Math.random() * weightsScores.length); +} +function getSupportedInstances(instanceList) { + const rawList = Object.values(instanceList).map(({ instanceAddress }) => { + return Object.values(instanceAddress); + }).flat(); + return rawList.map((l) => (0,ethers__WEBPACK_IMPORTED_MODULE_5__/* .getAddress */ .b)(l)); +} +function pickWeightedRandomRelayer(relayers, netId) { + let minFee, maxFee; + if (netId !== _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET) { + minFee = 0.01; + maxFee = 0.3; + } + const weightsScores = relayers.map((el) => calculateScore(el, minFee, maxFee)); + const totalWeight = weightsScores.reduce((acc, curr) => { + return acc = acc + curr; + }, BigInt("0")); + const random = BigInt(Number(totalWeight) * Math.random()); + const weightRandomIndex = getWeightRandom(weightsScores, random); + return relayers[weightRandomIndex]; +} +class RelayerClient { + constructor({ netId, config, Aggregator, fetchDataOptions: fetchDataOptions2 }) { + this.netId = netId; + this.config = config; + this.Aggregator = Aggregator; + this.fetchDataOptions = fetchDataOptions2; + } + askRelayerStatus(_0) { + return __async(this, arguments, function* ({ + hostname, + relayerAddress + }) { + var _a, _b; + const url = `https://${!hostname.endsWith("/") ? hostname + "/" : hostname}`; + const rawStatus = yield (0,_providers__WEBPACK_IMPORTED_MODULE_2__/* .fetchData */ .Fd)(`${url}status`, __spreadProps(__spreadValues({}, this.fetchDataOptions), { + headers: { + "Content-Type": "application/json, application/x-www-form-urlencoded" + }, + timeout: ((_a = this.fetchDataOptions) == null ? void 0 : _a.torPort) ? 1e4 : 3e3, + maxRetry: ((_b = this.fetchDataOptions) == null ? void 0 : _b.torPort) ? 2 : 0 + })); + const statusValidator = _schemas__WEBPACK_IMPORTED_MODULE_3__/* .ajv */ .SS.compile((0,_schemas__WEBPACK_IMPORTED_MODULE_3__/* .getStatusSchema */ .c_)(this.netId, this.config)); + if (!statusValidator(rawStatus)) { + throw new Error("Invalid status schema"); + } + const status = __spreadProps(__spreadValues({}, rawStatus), { + url + }); + if (status.currentQueue > 5) { + throw new Error("Withdrawal queue is overloaded"); + } + if (status.netId !== this.netId) { + throw new Error("This relayer serves a different network"); + } + if (relayerAddress && this.netId === _networkConfig__WEBPACK_IMPORTED_MODULE_1__/* .NetId */ .zr.MAINNET && status.rewardAccount !== relayerAddress) { + throw new Error("The Relayer reward address must match registered address"); + } + if (!isRelayerUpdated(status.version, this.netId)) { + throw new Error("Outdated version."); + } + return status; + }); + } + filterRelayer(curr, relayer, subdomains, debugRelayer = false) { + return __async(this, null, function* () { + var _a; + const { ensSubdomainKey } = this.config; + const subdomainIndex = subdomains.indexOf(ensSubdomainKey); + const mainnetSubdomain = curr.records[0]; + const hostname = curr.records[subdomainIndex]; + const isHostWithProtocol = hostname.includes("http"); + const { owner, balance: stakeBalance, isRegistered } = curr; + const { ensName, relayerAddress } = relayer; + const isOwner = !relayerAddress || relayerAddress === owner; + const hasMinBalance = stakeBalance >= MIN_STAKE_BALANCE; + const preCondition = hostname && isOwner && mainnetSubdomain && isRegistered && hasMinBalance && !isHostWithProtocol; + if (preCondition || debugRelayer) { + try { + const status = yield this.askRelayerStatus({ hostname, relayerAddress }); + return { + netId: status.netId, + url: status.url, + hostname, + ensName, + stakeBalance, + relayerAddress, + rewardAccount: (0,ethers__WEBPACK_IMPORTED_MODULE_5__/* .getAddress */ .b)(status.rewardAccount), + instances: getSupportedInstances(status.instances), + gasPrice: (_a = status.gasPrices) == null ? void 0 : _a.fast, + ethPrices: status.ethPrices, + currentQueue: status.currentQueue, + tornadoServiceFee: status.tornadoServiceFee + }; + } catch (err) { + if (debugRelayer) { + throw err; + } + return { + hostname, + relayerAddress, + errorMessage: err.message + }; + } + } else { + if (debugRelayer) { + const errMsg = `Relayer ${hostname} condition not met`; + throw new Error(errMsg); + } + return { + hostname, + relayerAddress, + errorMessage: `Relayer ${hostname} condition not met` + }; + } + }); + } + getValidRelayers(relayers, subdomains, debugRelayer = false) { + return __async(this, null, function* () { + const relayersSet = /* @__PURE__ */ new Set(); + const uniqueRelayers = relayers.reverse().filter(({ ensName }) => { + if (!relayersSet.has(ensName)) { + relayersSet.add(ensName); + return true; + } + return false; + }); + const relayerNameHashes = uniqueRelayers.map((r) => (0,ethers__WEBPACK_IMPORTED_MODULE_6__/* .namehash */ .kM)(r.ensName)); + const relayersData = yield this.Aggregator.relayersData.staticCall(relayerNameHashes, subdomains); + const invalidRelayers = []; + const validRelayers = (yield Promise.all( + relayersData.map((curr, index) => this.filterRelayer(curr, uniqueRelayers[index], subdomains, debugRelayer)) + )).filter((r) => { + if (r.errorMessage) { + invalidRelayers.push(r); + return false; + } + return true; + }); + return { + validRelayers, + invalidRelayers + }; + }); + } + pickWeightedRandomRelayer(relayers) { + return pickWeightedRandomRelayer(relayers, this.netId); + } + tornadoWithdraw(_0) { + return __async(this, arguments, function* ({ contract, proof, args }) { + const { url } = this.selectedRelayer; + const withdrawResponse = yield (0,_providers__WEBPACK_IMPORTED_MODULE_2__/* .fetchData */ .Fd)(`${url}v1/tornadoWithdraw`, __spreadProps(__spreadValues({}, this.fetchDataOptions), { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + contract, + proof, + args + }) + })); + const { id, error } = withdrawResponse; + if (error) { + throw new Error(error); + } + let relayerStatus; + const jobUrl = `${url}v1/jobs/${id}`; + console.log(`Job submitted: ${jobUrl} +`); + while (!relayerStatus || !["FAILED", "CONFIRMED"].includes(relayerStatus)) { + const jobResponse = yield (0,_providers__WEBPACK_IMPORTED_MODULE_2__/* .fetchData */ .Fd)(jobUrl, __spreadProps(__spreadValues({}, this.fetchDataOptions), { + method: "GET", + headers: { + "Content-Type": "application/json" + } + })); + if (jobResponse.error) { + throw new Error(error); + } + const jobValidator = _schemas__WEBPACK_IMPORTED_MODULE_3__/* .ajv */ .SS.compile(_schemas__WEBPACK_IMPORTED_MODULE_3__/* .jobsSchema */ .Us); + if (!jobValidator(jobResponse)) { + const errMsg = `${jobUrl} has an invalid job response`; + throw new Error(errMsg); + } + const { status, txHash, confirmations, failedReason } = jobResponse; + if (relayerStatus !== status) { + if (status === "FAILED") { + const errMsg = `Job ${status}: ${jobUrl} failed reason: ${failedReason}`; + throw new Error(errMsg); + } else if (status === "SENT") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash} +`); + } else if (status === "MINED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else if (status === "CONFIRMED") { + console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations} +`); + } else { + console.log(`Job ${status}: ${jobUrl} +`); + } + relayerStatus = status; + } + yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .sleep */ .yy)(3e3); + } + }); + } +} + + +/***/ }), + +/***/ 7613: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + SS: () => (/* binding */ schemas_ajv), + c_: () => (/* reexport */ getStatusSchema), + Us: () => (/* reexport */ jobsSchema) +}); + +// EXTERNAL MODULE: ./node_modules/ajv/dist/ajv.js +var ajv = __webpack_require__(63282); +var ajv_default = /*#__PURE__*/__webpack_require__.n(ajv); +// EXTERNAL MODULE: ./src/networkConfig.ts +var networkConfig = __webpack_require__(59499); +;// CONCATENATED MODULE: ./src/schemas/status.ts + + +const addressType = { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }; +const bnType = { type: "string", BN: true }; +const statusSchema = { + type: "object", + properties: { + rewardAccount: addressType, + gasPrices: { + type: "object", + properties: { + fast: { type: "number" }, + additionalProperties: { type: "number" } + }, + required: ["fast"] + }, + netId: { type: "integer" }, + tornadoServiceFee: { type: "number", maximum: 20, minimum: 0 }, + latestBlock: { type: "number" }, + version: { type: "string" }, + health: { + type: "object", + properties: { + status: { const: "true" }, + error: { type: "string" } + }, + required: ["status"] + }, + currentQueue: { type: "number" } + }, + required: ["rewardAccount", "instances", "netId", "tornadoServiceFee", "version", "health"] +}; +function getStatusSchema(netId, config) { + const { tokens, optionalTokens = [], nativeCurrency } = config; + const schema = JSON.parse(JSON.stringify(statusSchema)); + const instances = Object.keys(tokens).reduce( + (acc, token) => { + const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token]; + const amounts = Object.keys(instanceAddress); + const instanceProperties = { + type: "object", + properties: { + instanceAddress: { + type: "object", + properties: amounts.reduce((acc2, cur) => { + acc2[cur] = addressType; + return acc2; + }, {}), + required: amounts.filter((amount) => !optionalInstances.includes(amount)) + }, + decimals: { enum: [decimals] } + }, + required: ["instanceAddress", "decimals"].concat( + tokenAddress ? ["tokenAddress"] : [], + symbol ? ["symbol"] : [] + ) + }; + if (tokenAddress) { + instanceProperties.properties.tokenAddress = addressType; + } + if (symbol) { + instanceProperties.properties.symbol = { enum: [symbol] }; + } + acc.properties[token] = instanceProperties; + if (!optionalTokens.includes(token)) { + acc.required.push(token); + } + return acc; + }, + { + type: "object", + properties: {}, + required: [] + } + ); + schema.properties.instances = instances; + if (netId === networkConfig/* NetId */.zr.MAINNET) { + const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); + const ethPrices = { + type: "object", + properties: _tokens.reduce((acc, token) => { + acc[token] = bnType; + return acc; + }, {}) + // required: _tokens + }; + schema.properties.ethPrices = ethPrices; + } + return schema; +} + +;// CONCATENATED MODULE: ./src/schemas/jobs.ts + +const jobsSchema = { + type: "object", + properties: { + error: { type: "string" }, + id: { type: "string" }, + type: { type: "string" }, + status: { type: "string" }, + contract: { type: "string" }, + proof: { type: "string" }, + args: { + type: "array", + items: { type: "string" } + }, + txHash: { type: "string" }, + confirmations: { type: "number" }, + failedReason: { type: "string" } + }, + required: ["id", "status"] +}; + +;// CONCATENATED MODULE: ./src/schemas/index.ts + + +const schemas_ajv = new (ajv_default())({ allErrors: true }); +schemas_ajv.addKeyword({ + keyword: "BN", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validate: (schema, data) => { + try { + BigInt(data); + return true; + } catch (e) { + return false; + } + }, + errors: true +}); + + + + +/***/ }), + +/***/ 7393: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ H: () => (/* binding */ getTokenBalances) +/* harmony export */ }); +/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98982); +/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67276); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67418); +/* harmony import */ var _multicall__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48486); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + +function getTokenBalances(_0) { + return __async(this, arguments, function* ({ + provider, + Multicall: Multicall2, + currencyName, + userAddress, + tokenAddresses = [] + }) { + const tokenCalls = tokenAddresses.map((tokenAddress) => { + const Token = _typechain__WEBPACK_IMPORTED_MODULE_0__/* .ERC20__factory */ .Xc.connect(tokenAddress, provider); + return [ + { + contract: Token, + name: "balanceOf", + params: [userAddress] + }, + { + contract: Token, + name: "name" + }, + { + contract: Token, + name: "symbol" + }, + { + contract: Token, + name: "decimals" + } + ]; + }).flat(); + const multicallResults = yield (0,_multicall__WEBPACK_IMPORTED_MODULE_2__/* .multicall */ .C)(Multicall2, [ + { + contract: Multicall2, + name: "getEthBalance", + params: [userAddress] + }, + ...tokenCalls.length ? tokenCalls : [] + ]); + const ethResults = multicallResults[0]; + const tokenResults = multicallResults.slice(1).length ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .chunk */ .iv)(multicallResults.slice(1), tokenCalls.length / tokenAddresses.length) : []; + const tokenBalances = tokenResults.map((tokenResult, index) => { + const [tokenBalance, tokenName, tokenSymbol, tokenDecimals] = tokenResult; + const tokenAddress = tokenAddresses[index]; + return { + address: tokenAddress, + name: tokenName, + symbol: tokenSymbol, + decimals: Number(tokenDecimals), + balance: tokenBalance + }; + }); + return [ + { + address: ethers__WEBPACK_IMPORTED_MODULE_3__/* .ZeroAddress */ .j, + name: currencyName, + symbol: currencyName, + decimals: 18, + balance: ethResults + }, + ...tokenBalances + ]; + }); +} + + +/***/ }), + +/***/ 15609: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ v: () => (/* binding */ TreeCache) +/* harmony export */ }); +/* harmony import */ var bloomfilter_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65403); +/* harmony import */ var bloomfilter_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bloomfilter_js__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11489); +/* provided dependency */ var console = __webpack_require__(96763); + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; +}; +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + +class TreeCache { + constructor({ netId, amount, currency, userDirectory, PARTS_COUNT = 4 }) { + this.netId = netId; + this.amount = amount; + this.currency = currency; + this.userDirectory = userDirectory; + this.PARTS_COUNT = PARTS_COUNT; + } + getInstanceName() { + return `deposits_${this.netId}_${this.currency}_${this.amount}`; + } + createTree(events, tree) { + return __async(this, null, function* () { + const bloom = new (bloomfilter_js__WEBPACK_IMPORTED_MODULE_0___default())(events.length); + console.log(`Creating cached tree for ${this.getInstanceName()} +`); + const eventsData = events.reduce( + (acc, _a, i) => { + var _b = _a, { leafIndex, commitment } = _b, rest = __objRest(_b, ["leafIndex", "commitment"]); + if (leafIndex !== i) { + throw new Error(`leafIndex (${leafIndex}) !== i (${i})`); + } + acc[commitment] = __spreadProps(__spreadValues({}, rest), { leafIndex }); + return acc; + }, + {} + ); + const slices = tree.getTreeSlices(this.PARTS_COUNT); + yield Promise.all( + slices.map((slice, index) => __async(this, null, function* () { + const metadata = slice.elements.reduce((acc, curr) => { + if (index < this.PARTS_COUNT - 1) { + bloom.add(curr); + } + acc.push(eventsData[curr]); + return acc; + }, []); + const dataString2 = JSON.stringify( + __spreadProps(__spreadValues({}, slice), { + metadata + }), + null, + 2 + ) + "\n"; + const fileName2 = `${this.getInstanceName()}_slice${index + 1}.json`; + yield (0,_data__WEBPACK_IMPORTED_MODULE_1__/* .saveUserFile */ .jj)({ + fileName: fileName2, + userDirectory: this.userDirectory, + dataString: dataString2 + }); + })) + ); + const dataString = bloom.serialize() + "\n"; + const fileName = `${this.getInstanceName()}_bloom.json`; + yield (0,_data__WEBPACK_IMPORTED_MODULE_1__/* .saveUserFile */ .jj)({ + fileName, + userDirectory: this.userDirectory, + dataString + }); + }); + } +} + + +/***/ }), + +/***/ 67276: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + p2: () => (/* reexport */ ENS__factory), + Xc: () => (/* reexport */ ERC20__factory), + Hu: () => (/* reexport */ GasPriceOracle__factory), + Q2: () => (/* reexport */ Multicall__factory), + Hk: () => (/* reexport */ OffchainOracle__factory), + Ld: () => (/* reexport */ OvmGasPriceOracle__factory), + Rp: () => (/* reexport */ ReverseRecords__factory), + XB: () => (/* reexport */ factories_namespaceObject) +}); + +// NAMESPACE OBJECT: ./src/typechain/factories/index.ts +var factories_namespaceObject = {}; +__webpack_require__.r(factories_namespaceObject); +__webpack_require__.d(factories_namespaceObject, { + ENS__factory: () => (ENS__factory), + ERC20__factory: () => (ERC20__factory), + GasPriceOracle__factory: () => (GasPriceOracle__factory), + Multicall__factory: () => (Multicall__factory), + OffchainOracle__factory: () => (OffchainOracle__factory), + OvmGasPriceOracle__factory: () => (OvmGasPriceOracle__factory), + ReverseRecords__factory: () => (ReverseRecords__factory) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/interface.js +var abi_interface = __webpack_require__(73622); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/contract/contract.js + 1 modules +var contract = __webpack_require__(24391); +;// CONCATENATED MODULE: ./src/typechain/factories/ENS__factory.ts + + +const _abi = [ + { + constant: true, + inputs: [ + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "supportsInterface", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "pure", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + }, + { + internalType: "string", + name: "value", + type: "string" + } + ], + name: "setText", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + } + ], + name: "interfaceImplementer", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentTypes", + type: "uint256" + } + ], + name: "ABI", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + }, + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "setPubkey", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "setContenthash", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "addr", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "setAuthorisation", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "key", + type: "string" + } + ], + name: "text", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "contentType", + type: "uint256" + }, + { + internalType: "bytes", + name: "data", + type: "bytes" + } + ], + name: "setABI", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "string", + name: "name", + type: "string" + } + ], + name: "setName", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + internalType: "bytes", + name: "a", + type: "bytes" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "contenthash", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + } + ], + name: "pubkey", + outputs: [ + { + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "address", + name: "a", + type: "address" + } + ], + name: "setAddr", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "setInterface", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + internalType: "uint256", + name: "coinType", + type: "uint256" + } + ], + name: "addr", + outputs: [ + { + internalType: "bytes", + name: "", + type: "bytes" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + }, + { + internalType: "address", + name: "", + type: "address" + }, + { + internalType: "address", + name: "", + type: "address" + } + ], + name: "authorisations", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + payable: false, + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "target", + type: "address" + }, + { + indexed: false, + internalType: "bool", + name: "isAuthorised", + type: "bool" + } + ], + name: "AuthorisationChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "indexedKey", + type: "string" + }, + { + indexed: false, + internalType: "string", + name: "key", + type: "string" + } + ], + name: "TextChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "x", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes32", + name: "y", + type: "bytes32" + } + ], + name: "PubkeyChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "string", + name: "name", + type: "string" + } + ], + name: "NameChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "bytes4", + name: "interfaceID", + type: "bytes4" + }, + { + indexed: false, + internalType: "address", + name: "implementer", + type: "address" + } + ], + name: "InterfaceChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "bytes", + name: "hash", + type: "bytes" + } + ], + name: "ContenthashChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "address", + name: "a", + type: "address" + } + ], + name: "AddrChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: false, + internalType: "uint256", + name: "coinType", + type: "uint256" + }, + { + indexed: false, + internalType: "bytes", + name: "newAddress", + type: "bytes" + } + ], + name: "AddressChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "node", + type: "bytes32" + }, + { + indexed: true, + internalType: "uint256", + name: "contentType", + type: "uint256" + } + ], + name: "ABIChanged", + type: "event" + } +]; +class ENS__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, _abi, runner); + } +} +ENS__factory.abi = _abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/ERC20__factory.ts + + +const ERC20_factory_abi = [ + { + constant: true, + inputs: [], + name: "totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "_totalSupply", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "who", + type: "address" + } + ], + name: "balanceOf", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "name", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "symbol", + outputs: [ + { + internalType: "string", + name: "", + type: "string" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: true, + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transfer", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "owner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "spender", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Approval", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "from", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "to", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "Transfer", + type: "event" + }, + { + constant: true, + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + } + ], + name: "allowance", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + payable: false, + stateMutability: "view", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "from", + type: "address" + }, + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transferFrom", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + constant: false, + inputs: [ + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "approve", + outputs: [], + payable: false, + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + } + ], + name: "nonces", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "address", + name: "spender", + type: "address" + }, + { + internalType: "uint256", + name: "amount", + type: "uint256" + }, + { + internalType: "uint256", + name: "deadline", + type: "uint256" + }, + { + internalType: "uint8", + name: "v", + type: "uint8" + }, + { + internalType: "bytes32", + name: "r", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "s", + type: "bytes32" + } + ], + name: "permit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class ERC20__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(ERC20_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, ERC20_factory_abi, runner); + } +} +ERC20__factory.abi = ERC20_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/GasPriceOracle__factory.ts + + +const GasPriceOracle_factory_abi = [ + { + inputs: [], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "GAS_UNIT", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_derivationThresold", + type: "uint32" + } + ], + name: "changeDerivationThresold", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasUnit", + type: "uint32" + } + ], + name: "changeGasUnit", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_heartbeat", + type: "uint32" + } + ], + name: "changeHeartbeat", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + name: "changeOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "derivationThresold", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "heartbeat", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "maxPriorityFeePerGas", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "pastGasPrice", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint32", + name: "_gasPrice", + type: "uint32" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "timestamp", + outputs: [ + { + internalType: "uint32", + name: "", + type: "uint32" + } + ], + stateMutability: "view", + type: "function" + } +]; +class GasPriceOracle__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(GasPriceOracle_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, GasPriceOracle_factory_abi, runner); + } +} +GasPriceOracle__factory.abi = GasPriceOracle_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/Multicall__factory.ts + + +const Multicall_factory_abi = [ + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes[]", + name: "returnData", + type: "bytes[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bool", + name: "allowFailure", + type: "bool" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call3Value[]", + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3Value", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "blockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [], + name: "getBasefee", + outputs: [ + { + internalType: "uint256", + name: "basefee", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + name: "getBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getBlockNumber", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getChainId", + outputs: [ + { + internalType: "uint256", + name: "chainid", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockCoinbase", + outputs: [ + { + internalType: "address", + name: "coinbase", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockDifficulty", + outputs: [ + { + internalType: "uint256", + name: "difficulty", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockGasLimit", + outputs: [ + { + internalType: "uint256", + name: "gaslimit", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockTimestamp", + outputs: [ + { + internalType: "uint256", + name: "timestamp", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "addr", + type: "address" + } + ], + name: "getEthBalance", + outputs: [ + { + internalType: "uint256", + name: "balance", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getLastBlockHash", + outputs: [ + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryAggregate", + outputs: [ + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "bool", + name: "requireSuccess", + type: "bool" + }, + { + components: [ + { + internalType: "address", + name: "target", + type: "address" + }, + { + internalType: "bytes", + name: "callData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Call[]", + name: "calls", + type: "tuple[]" + } + ], + name: "tryBlockAndAggregate", + outputs: [ + { + internalType: "uint256", + name: "blockNumber", + type: "uint256" + }, + { + internalType: "bytes32", + name: "blockHash", + type: "bytes32" + }, + { + components: [ + { + internalType: "bool", + name: "success", + type: "bool" + }, + { + internalType: "bytes", + name: "returnData", + type: "bytes" + } + ], + internalType: "struct Multicall3.Result[]", + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "payable", + type: "function" + } +]; +class Multicall__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(Multicall_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, Multicall_factory_abi, runner); + } +} +Multicall__factory.abi = Multicall_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/OffchainOracle__factory.ts + + +const OffchainOracle_factory_abi = [ + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + }, + { + internalType: "contract IOracle[]", + name: "existingOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + }, + { + internalType: "contract IERC20[]", + name: "existingConnectors", + type: "address[]" + }, + { + internalType: "contract IERC20", + name: "wBase", + type: "address" + }, + { + internalType: "address", + name: "owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "ArraysLengthMismatch", + type: "error" + }, + { + inputs: [], + name: "ConnectorAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "InvalidOracleTokenKind", + type: "error" + }, + { + inputs: [], + name: "OracleAlreadyAdded", + type: "error" + }, + { + inputs: [], + name: "SameTokens", + type: "error" + }, + { + inputs: [], + name: "TooBigThreshold", + type: "error" + }, + { + inputs: [], + name: "UnknownConnector", + type: "error" + }, + { + inputs: [], + name: "UnknownOracle", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "ConnectorRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract MultiWrapper", + name: "multiWrapper", + type: "address" + } + ], + name: "MultiWrapperUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleAdded", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + indexed: false, + internalType: "enum OffchainOracle.OracleType", + name: "oracleType", + type: "uint8" + } + ], + name: "OracleRemoved", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "addConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "addOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "connectors", + outputs: [ + { + internalType: "contract IERC20[]", + name: "allConnectors", + type: "address[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + } + ], + name: "getRate", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + } + ], + name: "getRateToEth", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "bool", + name: "useSrcWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateToEthWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "contract IERC20[]", + name: "customConnectors", + type: "address[]" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithCustomConnectors", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "srcToken", + type: "address" + }, + { + internalType: "contract IERC20", + name: "dstToken", + type: "address" + }, + { + internalType: "bool", + name: "useWrappers", + type: "bool" + }, + { + internalType: "uint256", + name: "thresholdFilter", + type: "uint256" + } + ], + name: "getRateWithThreshold", + outputs: [ + { + internalType: "uint256", + name: "weightedRate", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "multiWrapper", + outputs: [ + { + internalType: "contract MultiWrapper", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "oracles", + outputs: [ + { + internalType: "contract IOracle[]", + name: "allOracles", + type: "address[]" + }, + { + internalType: "enum OffchainOracle.OracleType[]", + name: "oracleTypes", + type: "uint8[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IERC20", + name: "connector", + type: "address" + } + ], + name: "removeConnector", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract IOracle", + name: "oracle", + type: "address" + }, + { + internalType: "enum OffchainOracle.OracleType", + name: "oracleKind", + type: "uint8" + } + ], + name: "removeOracle", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "contract MultiWrapper", + name: "_multiWrapper", + type: "address" + } + ], + name: "setMultiWrapper", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OffchainOracle__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(OffchainOracle_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, OffchainOracle_factory_abi, runner); + } +} +OffchainOracle__factory.abi = OffchainOracle_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/OvmGasPriceOracle__factory.ts + + +const OvmGasPriceOracle_factory_abi = [ + { + inputs: [ + { + internalType: "address", + name: "_owner", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "DecimalsUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "GasPriceUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "L1BaseFeeUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "OverheadUpdated", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "previousOwner", + type: "address" + }, + { + indexed: true, + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "OwnershipTransferred", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "uint256", + name: "", + type: "uint256" + } + ], + name: "ScalarUpdated", + type: "event" + }, + { + inputs: [], + name: "decimals", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "gasPrice", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1Fee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes", + name: "_data", + type: "bytes" + } + ], + name: "getL1GasUsed", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "l1BaseFee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "overhead", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "renounceOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "scalar", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_decimals", + type: "uint256" + } + ], + name: "setDecimals", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_gasPrice", + type: "uint256" + } + ], + name: "setGasPrice", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_baseFee", + type: "uint256" + } + ], + name: "setL1BaseFee", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_overhead", + type: "uint256" + } + ], + name: "setOverhead", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "_scalar", + type: "uint256" + } + ], + name: "setScalar", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "newOwner", + type: "address" + } + ], + name: "transferOwnership", + outputs: [], + stateMutability: "nonpayable", + type: "function" + } +]; +class OvmGasPriceOracle__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(OvmGasPriceOracle_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, OvmGasPriceOracle_factory_abi, runner); + } +} +OvmGasPriceOracle__factory.abi = OvmGasPriceOracle_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/ReverseRecords__factory.ts + + +const ReverseRecords_factory_abi = [ + { + inputs: [ + { + internalType: "contract ENS", + name: "_ens", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + internalType: "address[]", + name: "addresses", + type: "address[]" + } + ], + name: "getNames", + outputs: [ + { + internalType: "string[]", + name: "r", + type: "string[]" + } + ], + stateMutability: "view", + type: "function" + } +]; +class ReverseRecords__factory { + static createInterface() { + return new abi_interface/* Interface */.KA(ReverseRecords_factory_abi); + } + static connect(address, runner) { + return new contract/* Contract */.NZ(address, ReverseRecords_factory_abi, runner); + } +} +ReverseRecords__factory.abi = ReverseRecords_factory_abi; + +;// CONCATENATED MODULE: ./src/typechain/factories/index.ts + + + + + + + + + +;// CONCATENATED MODULE: ./src/typechain/index.ts + + + + + + + + + + + + +/***/ }), + +/***/ 67418: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $W: () => (/* binding */ toFixedHex), +/* harmony export */ EI: () => (/* binding */ leInt2Buff), +/* harmony export */ Et: () => (/* binding */ crypto), +/* harmony export */ Id: () => (/* binding */ concatBytes), +/* harmony export */ Ju: () => (/* binding */ bytesToBN), +/* harmony export */ Kp: () => (/* binding */ base64ToBytes), +/* harmony export */ Ll: () => (/* binding */ isNode), +/* harmony export */ My: () => (/* binding */ bytesToHex), +/* harmony export */ aT: () => (/* binding */ hexToBytes), +/* harmony export */ ae: () => (/* binding */ leBuff2Int), +/* harmony export */ gn: () => (/* binding */ bigIntReplacer), +/* harmony export */ ib: () => (/* binding */ rBigInt), +/* harmony export */ "if": () => (/* binding */ bytesToBase64), +/* harmony export */ iv: () => (/* binding */ chunk), +/* harmony export */ jm: () => (/* binding */ bnToBytes), +/* harmony export */ lY: () => (/* binding */ bufferToBytes), +/* harmony export */ sY: () => (/* binding */ toFixedLength), +/* harmony export */ uU: () => (/* binding */ substring), +/* harmony export */ wv: () => (/* binding */ validateUrl), +/* harmony export */ yy: () => (/* binding */ sleep) +/* harmony export */ }); +/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(91565); +/* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(39404); +/* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(bn_js__WEBPACK_IMPORTED_MODULE_1__); +/* provided dependency */ var process = __webpack_require__(65606); + + + +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; +const crypto = isNode ? crypto__WEBPACK_IMPORTED_MODULE_0__.webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new (bn_js__WEBPACK_IMPORTED_MODULE_1___default())(bytes, 16, "le"); +} +function leInt2Buff(bigint) { + return Uint8Array.from(new (bn_js__WEBPACK_IMPORTED_MODULE_1___default())(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + + +/***/ }), + +/***/ 26746: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ i: () => (/* binding */ calculateSnarkProof) +/* harmony export */ }); +/* harmony import */ var _tornado_websnark_src_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84276); +/* harmony import */ var _tornado_websnark_src_utils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_tornado_websnark_src_utils__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36336); +/* harmony import */ var _tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67418); +/* provided dependency */ var console = __webpack_require__(96763); + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + +let groth16; +const groth16Promise = (() => __async(void 0, null, function* () { + if (!groth16) { + groth16 = yield _tornado_websnark_src_groth16__WEBPACK_IMPORTED_MODULE_1___default()({ wasmInitialMemory: 2e3 }); + } +}))(); +function calculateSnarkProof(input, circuit, provingKey) { + return __async(this, null, function* () { + yield groth16Promise; + const snarkInput = { + root: input.root, + nullifierHash: BigInt(input.nullifierHex).toString(), + recipient: BigInt(input.recipient), + relayer: BigInt(input.relayer), + fee: input.fee, + refund: input.refund, + nullifier: input.nullifier, + secret: input.secret, + pathElements: input.pathElements, + pathIndices: input.pathIndices + }; + console.log("Start generating SNARK proof", snarkInput); + console.time("SNARK proof time"); + const proofData = yield _tornado_websnark_src_utils__WEBPACK_IMPORTED_MODULE_0__.genWitnessAndProve(groth16, snarkInput, circuit, provingKey); + const proof = _tornado_websnark_src_utils__WEBPACK_IMPORTED_MODULE_0__.toSolidityInput(proofData).proof; + console.timeEnd("SNARK proof time"); + const args = [ + (0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(input.root, 32), + (0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(input.nullifierHex, 32), + input.recipient, + input.relayer, + (0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(input.fee, 32), + (0,_utils__WEBPACK_IMPORTED_MODULE_2__/* .toFixedHex */ .$W)(input.refund, 32) + ]; + return { proof, args }; + }); +} + + +/***/ }), + +/***/ 32019: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.keccak512 = exports.keccak384 = exports.keccak256 = exports.keccak224 = void 0; +const sha3_1 = __webpack_require__(32955); +const utils_js_1 = __webpack_require__(82672); +exports.keccak224 = (0, utils_js_1.wrapHash)(sha3_1.keccak_224); +exports.keccak256 = (() => { + const k = (0, utils_js_1.wrapHash)(sha3_1.keccak_256); + k.create = sha3_1.keccak_256.create; + return k; +})(); +exports.keccak384 = (0, utils_js_1.wrapHash)(sha3_1.keccak_384); +exports.keccak512 = (0, utils_js_1.wrapHash)(sha3_1.keccak_512); + + +/***/ }), + +/***/ 26513: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.secp256k1 = void 0; +var secp256k1_1 = __webpack_require__(8510); +Object.defineProperty(exports, "secp256k1", ({ enumerable: true, get: function () { return secp256k1_1.secp256k1; } })); + + +/***/ }), + +/***/ 82672: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.crypto = exports.wrapHash = exports.equalsBytes = exports.hexToBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0; +const _assert_1 = __importDefault(__webpack_require__(67557)); +const utils_1 = __webpack_require__(99175); +const assertBool = _assert_1.default.bool; +exports.assertBool = assertBool; +const assertBytes = _assert_1.default.bytes; +exports.assertBytes = assertBytes; +var utils_2 = __webpack_require__(99175); +Object.defineProperty(exports, "bytesToHex", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } })); +Object.defineProperty(exports, "toHex", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } })); +Object.defineProperty(exports, "concatBytes", ({ enumerable: true, get: function () { return utils_2.concatBytes; } })); +Object.defineProperty(exports, "createView", ({ enumerable: true, get: function () { return utils_2.createView; } })); +Object.defineProperty(exports, "utf8ToBytes", ({ enumerable: true, get: function () { return utils_2.utf8ToBytes; } })); +// buf.toString('utf8') -> bytesToUtf8(buf) +function bytesToUtf8(data) { + if (!(data instanceof Uint8Array)) { + throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`); + } + return new TextDecoder().decode(data); +} +exports.bytesToUtf8 = bytesToUtf8; +function hexToBytes(data) { + const sliced = data.startsWith("0x") ? data.substring(2) : data; + return (0, utils_1.hexToBytes)(sliced); +} +exports.hexToBytes = hexToBytes; +// buf.equals(buf2) -> equalsBytes(buf, buf2) +function equalsBytes(a, b) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} +exports.equalsBytes = equalsBytes; +// Internal utils +function wrapHash(hash) { + return (msg) => { + _assert_1.default.bytes(msg); + return hash(msg); + }; +} +exports.wrapHash = wrapHash; +// TODO(v3): switch away from node crypto, remove this unnecessary variable. +exports.crypto = (() => { + const webCrypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; + const nodeRequire = true && + typeof module.require === "function" && + module.require.bind(module); + return { + node: nodeRequire && !webCrypto ? nodeRequire("crypto") : undefined, + web: webCrypto + }; +})(); + + +/***/ }), + +/***/ 37007: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(96763); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), + +/***/ 68078: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) +var MD5 = __webpack_require__(88276) + +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') + } + + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) + + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() + + var used = 0 + + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } + + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length + } + } + + tmp.fill(0) + return { key: key, iv: iv } +} + +module.exports = EVP_BytesToKey + + +/***/ }), + +/***/ 32017: +/***/ ((module) => { + +"use strict"; + + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; + + +/***/ }), + +/***/ 82682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isCallable = __webpack_require__(69600); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; + + +/***/ }), + +/***/ 89353: +/***/ ((module) => { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ 66743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(89353); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 70453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var undefined; + +var $Error = __webpack_require__(69383); +var $EvalError = __webpack_require__(41237); +var $RangeError = __webpack_require__(79290); +var $ReferenceError = __webpack_require__(79538); +var $SyntaxError = __webpack_require__(58068); +var $TypeError = __webpack_require__(69675); +var $URIError = __webpack_require__(35345); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(64039)(); +var hasProto = __webpack_require__(80024)(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(66743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ 75795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(70453); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ 30592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(30655); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ 80024: +/***/ ((module) => { + +"use strict"; + + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; + + +/***/ }), + +/***/ 64039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(41333); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ 41333: +/***/ ((module) => { + +"use strict"; + + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ 49092: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasSymbols = __webpack_require__(41333); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; + + +/***/ }), + +/***/ 77952: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var hash = exports; + +hash.utils = __webpack_require__(67426); +hash.common = __webpack_require__(66166); +hash.sha = __webpack_require__(46229); +hash.ripemd = __webpack_require__(46784); +hash.hmac = __webpack_require__(28948); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; + + +/***/ }), + +/***/ 66166: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var assert = __webpack_require__(43349); + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; + + +/***/ }), + +/***/ 28948: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var assert = __webpack_require__(43349); + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + + +/***/ }), + +/***/ 46784: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var common = __webpack_require__(66166); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + + +/***/ }), + +/***/ 46229: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.sha1 = __webpack_require__(43917); +exports.sha224 = __webpack_require__(47714); +exports.sha256 = __webpack_require__(2287); +exports.sha384 = __webpack_require__(21911); +exports.sha512 = __webpack_require__(57766); + + +/***/ }), + +/***/ 43917: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var common = __webpack_require__(66166); +var shaCommon = __webpack_require__(66225); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 47714: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var SHA256 = __webpack_require__(2287); + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + + + +/***/ }), + +/***/ 2287: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var common = __webpack_require__(66166); +var shaCommon = __webpack_require__(66225); +var assert = __webpack_require__(43349); + +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; + +var BlockHash = common.BlockHash; + +var sha256_K = [ + 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 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 21911: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); + +var SHA512 = __webpack_require__(57766); + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + + +/***/ }), + +/***/ 57766: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var common = __webpack_require__(66166); +var assert = __webpack_require__(43349); + +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; + +var BlockHash = common.BlockHash; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + + +/***/ }), + +/***/ 66225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(67426); +var rotr32 = utils.rotr32; + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +exports.ft_1 = ft_1; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +exports.ch32 = ch32; + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +exports.maj32 = maj32; + +function p32(x, y, z) { + return x ^ y ^ z; +} +exports.p32 = p32; + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} +exports.s0_256 = s0_256; + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} +exports.s1_256 = s1_256; + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} +exports.g0_256 = g0_256; + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} +exports.g1_256 = g1_256; + + +/***/ }), + +/***/ 67426: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(43349); +var inherits = __webpack_require__(56698); + +exports.inherits = inherits; + +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; +} + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + // Inspired by stringToUtf8ByteArray() in closure-library by Google + // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 + // Apache License 2.0 + // https://github.com/google/closure-library/blob/master/LICENSE + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = (c >> 6) | 192; + res[p++] = (c & 63) | 128; + } else if (isSurrogatePair(msg, i)) { + c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); + res[p++] = (c >> 18) | 240; + res[p++] = ((c >> 12) & 63) | 128; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } else { + res[p++] = (c >> 12) | 224; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +exports.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +exports.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +exports.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +exports.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +exports.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +exports.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +exports.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +exports.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +exports.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +exports.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +exports.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +exports.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +exports.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +exports.sum32_5 = sum32_5; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +} +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +} +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.shr64_lo = shr64_lo; + + +/***/ }), + +/***/ 9957: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(66743); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ 32723: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(77952); +var utils = __webpack_require__(64367); +var assert = __webpack_require__(43349); + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils.toArray(options.pers, options.persEnc || 'hex'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 11083: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var http = __webpack_require__(11568) +var url = __webpack_require__(23276) + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 56698: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 47244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasToStringTag = __webpack_require__(49092)(); +var callBound = __webpack_require__(38075); + +var $toString = callBound('Object.prototype.toString'); + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + $toString(value) !== '[object Array]' && + $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + + +/***/ }), + +/***/ 69600: +/***/ ((module) => { + +"use strict"; + + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; + + +/***/ }), + +/***/ 48184: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = __webpack_require__(49092)(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; + + +/***/ }), + +/***/ 13003: +/***/ ((module) => { + +"use strict"; + + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function isNaN(value) { + return value !== value; +}; + + +/***/ }), + +/***/ 24133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var callBind = __webpack_require__(10487); +var define = __webpack_require__(38452); + +var implementation = __webpack_require__(13003); +var getPolyfill = __webpack_require__(76642); +var shim = __webpack_require__(92464); + +var polyfill = callBind(getPolyfill(), Number); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 76642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(13003); + +module.exports = function getPolyfill() { + if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { + return Number.isNaN; + } + return implementation; +}; + + +/***/ }), + +/***/ 92464: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(38452); +var getPolyfill = __webpack_require__(76642); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function shimNumberIsNaN() { + var polyfill = getPolyfill(); + define(Number, { isNaN: polyfill }, { + isNaN: function testIsNaN() { + return Number.isNaN !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 35680: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var whichTypedArray = __webpack_require__(25767); + +/** @type {import('.')} */ +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; + + +/***/ }), + +/***/ 31176: +/***/ ((module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +var __WEBPACK_AMD_DEFINE_RESULT__;/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ +/*jslint bitwise: true */ +(function () { + 'use strict'; + + var INPUT_ERROR = 'input is invalid type'; + var FINALIZE_ERROR = 'finalize already called'; + var WINDOW = typeof window === 'object'; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === 'object'; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = __webpack_require__.g; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && "object" === 'object' && module.exports; + var AMD = true && __webpack_require__.amdO; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var CSHAKE_PADDING = [4, 1024, 262144, 67108864]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest']; + var CSHAKE_BYTEPAD = { + '128': 168, + '256': 136 + }; + + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + } + + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function (obj) { + return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createCshakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits, n, s) { + return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); + }; + }; + + var createKmacOutputMethod = function (bits, padding, outputType) { + return function (key, message, outputBits, s) { + return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); + }; + }; + + var createOutputMethods = function (method, createMethod, bits, padding) { + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createMethod(bits, padding, type); + } + return method; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits, padding); + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits, padding); + }; + + var createCshakeMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createCshakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits, n, s) { + if (!n && !s) { + return methods['shake' + bits].create(outputBits); + } else { + return new Keccak(bits, padding, outputBits).bytepad([n, s], w); + } + }; + method.update = function (message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits, padding); + }; + + var createKmacMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createKmacOutputMethod(bits, padding, 'hex'); + method.create = function (key, outputBits, s) { + return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w); + }; + method.update = function (key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits, padding); + }; + + var algorithms = [ + { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, + { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod }, + { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod }, + { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod }, + { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod } + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name + '_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== 'sha3') { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== 'string') { + if (type === 'object') { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.encode = function (x, right) { + var o = x & 255, n = 1; + var bytes = [o]; + x = x >> 8; + o = x & 255; + while (o > 0) { + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + + Keccak.prototype.encodeString = function (str) { + var notString, type = typeof str; + if (type !== 'string') { + if (type === 'object') { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for (var i = 0; i < str.length; ++i) { + var code = str.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code < 0xd800 || code >= 0xe000) { + bytes += 3; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + + Keccak.prototype.bytepad = function (strs, w) { + var bytes = this.encode(w); + for (var i = 0; i < strs.length; ++i) { + bytes += this.encodeString(strs[i]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + + Keccak.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + function Kmac(bits, padding, outputBits) { + Keccak.call(this, bits, padding, outputBits); + } + + Kmac.prototype = new Keccak(); + + Kmac.prototype.finalize = function () { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + if (AMD) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return methods; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } + } +})(); + + +/***/ }), + +/***/ 7106: +/***/ ((module) => { + +"use strict"; + + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i { + +"use strict"; + + +// A linked list to keep track of recently-used-ness +const Yallist = __webpack_require__(28799) + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache + + +/***/ }), + +/***/ 88276: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(56698) +var HashBase = __webpack_require__(73726) +var Buffer = (__webpack_require__(92861).Buffer) + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 + + +/***/ }), + +/***/ 73726: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(92861).Buffer) +var Transform = (__webpack_require__(28399).Transform) +var inherits = __webpack_require__(56698) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + + +/***/ }), + +/***/ 6215: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +/* provided dependency */ var process = __webpack_require__(65606); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InvalidStatusCodeError = exports.InvalidCertError = void 0; +const DEFAULT_OPT = Object.freeze({ + redirect: true, + expectStatusCode: 200, + headers: {}, + full: false, + keepAlive: true, + cors: false, + referrer: false, + sslAllowSelfSigned: false, + _redirectCount: 0, +}); +class InvalidCertError extends Error { + constructor(msg, fingerprint256) { + super(msg); + this.fingerprint256 = fingerprint256; + } +} +exports.InvalidCertError = InvalidCertError; +class InvalidStatusCodeError extends Error { + constructor(statusCode) { + super(`Request Failed. Status Code: ${statusCode}`); + this.statusCode = statusCode; + } +} +exports.InvalidStatusCodeError = InvalidStatusCodeError; +function detectType(b, type) { + if (!type || type === 'text' || type === 'json') { + try { + let text = new TextDecoder('utf8', { fatal: true }).decode(b); + if (type === 'text') + return text; + try { + return JSON.parse(text); + } + catch (err) { + if (type === 'json') + throw err; + return text; + } + } + catch (err) { + if (type === 'text' || type === 'json') + throw err; + } + } + return b; +} +let agents = {}; +function fetchNode(url, _options) { + let options = { ...DEFAULT_OPT, ..._options }; + const http = __webpack_require__(11568); + const https = __webpack_require__(11083); + const zlib = __webpack_require__(78559); + const { promisify } = __webpack_require__(40537); + const { resolve: urlResolve } = __webpack_require__(59676); + const isSecure = !!/^https/.test(url); + let opts = { + method: options.method || 'GET', + headers: { 'Accept-Encoding': 'gzip, deflate, br' }, + }; + const compactFP = (s) => s.replace(/:| /g, '').toLowerCase(); + if (options.keepAlive) { + const agentOpt = { + keepAlive: true, + keepAliveMsecs: 30 * 1000, + maxFreeSockets: 1024, + maxCachedSessions: 1024, + }; + const agentKey = [ + isSecure, + isSecure && options.sslPinnedCertificates?.map((i) => compactFP(i)).sort(), + ].join(); + opts.agent = + agents[agentKey] || (agents[agentKey] = new (isSecure ? https : http).Agent(agentOpt)); + } + if (options.type === 'json') + opts.headers['Content-Type'] = 'application/json'; + if (options.data) { + if (!options.method) + opts.method = 'POST'; + opts.body = options.type === 'json' ? JSON.stringify(options.data) : options.data; + } + opts.headers = { ...opts.headers, ...options.headers }; + if (options.sslAllowSelfSigned) + opts.rejectUnauthorized = false; + const handleRes = async (res) => { + const status = res.statusCode; + if (options.redirect && 300 <= status && status < 400 && res.headers['location']) { + if (options._redirectCount == 10) + throw new Error('Request failed. Too much redirects.'); + options._redirectCount += 1; + return await fetchNode(urlResolve(url, res.headers['location']), options); + } + if (options.expectStatusCode && status !== options.expectStatusCode) { + res.resume(); + throw new InvalidStatusCodeError(status); + } + let buf = []; + for await (const chunk of res) + buf.push(chunk); + let bytes = Buffer.concat(buf); + const encoding = res.headers['content-encoding']; + if (encoding === 'br') + bytes = await promisify(zlib.brotliDecompress)(bytes); + if (encoding === 'gzip' || encoding === 'deflate') + bytes = await promisify(zlib.unzip)(bytes); + const body = detectType(bytes, options.type); + if (options.full) + return { headers: res.headers, status, body }; + return body; + }; + return new Promise((resolve, reject) => { + const handleError = async (err) => { + if (err && err.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') { + try { + await fetchNode(url, { ...options, sslAllowSelfSigned: true, sslPinnedCertificates: [] }); + } + catch (e) { + if (e && e.fingerprint256) { + err = new InvalidCertError(`Self-signed SSL certificate: ${e.fingerprint256}`, e.fingerprint256); + } + } + } + reject(err); + }; + const req = (isSecure ? https : http).request(url, opts, (res) => { + res.on('error', handleError); + (async () => { + try { + resolve(await handleRes(res)); + } + catch (error) { + reject(error); + } + })(); + }); + req.on('error', handleError); + const pinned = options.sslPinnedCertificates?.map((i) => compactFP(i)); + const mfetchSecureConnect = (socket) => { + const fp256 = compactFP(socket.getPeerCertificate()?.fingerprint256 || ''); + if (!fp256 && socket.isSessionReused()) + return; + if (pinned.includes(fp256)) + return; + req.emit('error', new InvalidCertError(`Invalid SSL certificate: ${fp256} Expected: ${pinned}`, fp256)); + return req.abort(); + }; + if (options.sslPinnedCertificates) { + req.on('socket', (socket) => { + const hasListeners = socket + .listeners('secureConnect') + .map((i) => (i.name || '').replace('bound ', '')) + .includes('mfetchSecureConnect'); + if (hasListeners) + return; + socket.on('secureConnect', mfetchSecureConnect.bind(null, socket)); + }); + } + if (options.keepAlive) + req.setNoDelay(true); + if (opts.body) + req.write(opts.body); + req.end(); + }); +} +const SAFE_HEADERS = new Set(['Accept', 'Accept-Language', 'Content-Language', 'Content-Type'].map((i) => i.toLowerCase())); +const FORBIDDEN_HEADERS = new Set(['Accept-Charset', 'Accept-Encoding', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', + 'Connection', 'Content-Length', 'Cookie', 'Cookie2', 'Date', 'DNT', 'Expect', 'Host', 'Keep-Alive', 'Origin', 'Referer', 'TE', 'Trailer', + 'Transfer-Encoding', 'Upgrade', 'Via'].map((i) => i.toLowerCase())); +async function fetchBrowser(url, _options) { + let options = { ...DEFAULT_OPT, ..._options }; + const headers = new Headers(); + if (options.type === 'json') + headers.set('Content-Type', 'application/json'); + let parsed = new URL(url); + if (parsed.username) { + const auth = btoa(`${parsed.username}:${parsed.password}`); + headers.set('Authorization', `Basic ${auth}`); + parsed.username = ''; + parsed.password = ''; + } + url = '' + parsed; + for (let k in options.headers) { + const name = k.toLowerCase(); + if (SAFE_HEADERS.has(name) || (options.cors && !FORBIDDEN_HEADERS.has(name))) + headers.set(k, options.headers[k]); + } + let opts = { headers, redirect: options.redirect ? 'follow' : 'manual' }; + if (!options.referrer) + opts.referrerPolicy = 'no-referrer'; + if (options.cors) + opts.mode = 'cors'; + if (options.data) { + if (!options.method) + opts.method = 'POST'; + opts.body = options.type === 'json' ? JSON.stringify(options.data) : options.data; + } + const res = await fetch(url, opts); + if (options.expectStatusCode && res.status !== options.expectStatusCode) + throw new InvalidStatusCodeError(res.status); + const body = detectType(new Uint8Array(await res.arrayBuffer()), options.type); + if (options.full) + return { headers: Object.fromEntries(res.headers.entries()), status: res.status, body }; + return body; +} +const IS_NODE = !!(typeof process == 'object' && + process.versions && + process.versions.node && + process.versions.v8); +function fetchUrl(url, options) { + const fn = IS_NODE ? fetchNode : fetchBrowser; + return fn(url, options); +} +exports["default"] = fetchUrl; + + +/***/ }), + +/***/ 52244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var bn = __webpack_require__(61158); +var brorand = __webpack_require__(15037); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._randbelow = function _randbelow(n) { + var len = n.bitLength(); + var min_bytes = Math.ceil(len / 8); + + // Generage random bytes until a number less than n is found. + // This ensures that 0..n-1 have an equal probability of being selected. + do + var a = new bn(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + + return a; +}; + +MillerRabin.prototype._randrange = function _randrange(start, stop) { + // Generate a random number greater than or equal to start and less than stop. + var size = stop.sub(start); + return start.add(this._randbelow(size)); +}; + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return false; +}; + + +/***/ }), + +/***/ 61158: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(64688).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 43349: +/***/ ((module) => { + +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + + +/***/ }), + +/***/ 64367: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + + +/***/ }), + +/***/ 25177: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Afrikaans [af] +//! author : Werner Mollentze : https://github.com/wernerm + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var af = moment.defineLocale('af', { + months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), + weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split( + '_' + ), + weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), + weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), + meridiemParse: /vm|nm/i, + isPM: function (input) { + return /^nm$/i.test(input); + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'vm' : 'VM'; + } else { + return isLower ? 'nm' : 'NM'; + } + }, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Vandag om] LT', + nextDay: '[Môre om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[Gister om] LT', + lastWeek: '[Laas] dddd [om] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'oor %s', + past: '%s gelede', + s: "'n paar sekondes", + ss: '%d sekondes', + m: "'n minuut", + mm: '%d minute', + h: "'n uur", + hh: '%d ure', + d: "'n dag", + dd: '%d dae', + M: "'n maand", + MM: '%d maande', + y: "'n jaar", + yy: '%d jaar', + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal: function (number) { + return ( + number + + (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de') + ); // Thanks to Joris Röling : https://github.com/jjupiter + }, + week: { + dow: 1, // Maandag is die eerste dag van die week. + doy: 4, // Die week wat die 4de Januarie bevat is die eerste week van die jaar. + }, + }); + + return af; + +}))); + + +/***/ }), + +/***/ 41488: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Algeria) [ar-dz] +//! author : Amine Roukh: https://github.com/Amine27 +//! author : Abdel Said: https://github.com/abdelsaid +//! author : Ahmed Elkhatib +//! author : forabi https://github.com/forabi +//! author : Noureddine LOUAHEDJ : https://github.com/noureddinem + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var pluralForm = function (n) { + return n === 0 + ? 0 + : n === 1 + ? 1 + : n === 2 + ? 2 + : n % 100 >= 3 && n % 100 <= 10 + ? 3 + : n % 100 >= 11 + ? 4 + : 5; + }, + plurals = { + s: [ + 'أقل من ثانية', + 'ثانية واحدة', + ['ثانيتان', 'ثانيتين'], + '%d ثوان', + '%d ثانية', + '%d ثانية', + ], + m: [ + 'أقل من دقيقة', + 'دقيقة واحدة', + ['دقيقتان', 'دقيقتين'], + '%d دقائق', + '%d دقيقة', + '%d دقيقة', + ], + h: [ + 'أقل من ساعة', + 'ساعة واحدة', + ['ساعتان', 'ساعتين'], + '%d ساعات', + '%d ساعة', + '%d ساعة', + ], + d: [ + 'أقل من يوم', + 'يوم واحد', + ['يومان', 'يومين'], + '%d أيام', + '%d يومًا', + '%d يوم', + ], + M: [ + 'أقل من شهر', + 'شهر واحد', + ['شهران', 'شهرين'], + '%d أشهر', + '%d شهرا', + '%d شهر', + ], + y: [ + 'أقل من عام', + 'عام واحد', + ['عامان', 'عامين'], + '%d أعوام', + '%d عامًا', + '%d عام', + ], + }, + pluralize = function (u) { + return function (number, withoutSuffix, string, isFuture) { + var f = pluralForm(number), + str = plurals[u][pluralForm(number)]; + if (f === 2) { + str = str[withoutSuffix ? 0 : 1]; + } + return str.replace(/%d/i, number); + }; + }, + months = [ + 'جانفي', + 'فيفري', + 'مارس', + 'أفريل', + 'ماي', + 'جوان', + 'جويلية', + 'أوت', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', + ]; + + var arDz = moment.defineLocale('ar-dz', { + months: months, + monthsShort: months, + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'D/\u200FM/\u200FYYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ص|م/, + isPM: function (input) { + return 'م' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar: { + sameDay: '[اليوم عند الساعة] LT', + nextDay: '[غدًا عند الساعة] LT', + nextWeek: 'dddd [عند الساعة] LT', + lastDay: '[أمس عند الساعة] LT', + lastWeek: 'dddd [عند الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'بعد %s', + past: 'منذ %s', + s: pluralize('s'), + ss: pluralize('s'), + m: pluralize('m'), + mm: pluralize('m'), + h: pluralize('h'), + hh: pluralize('h'), + d: pluralize('d'), + dd: pluralize('d'), + M: pluralize('M'), + MM: pluralize('M'), + y: pluralize('y'), + yy: pluralize('y'), + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return arDz; + +}))); + + +/***/ }), + +/***/ 58676: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Kuwait) [ar-kw] +//! author : Nusret Parlak: https://github.com/nusretparlak + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var arKw = moment.defineLocale('ar-kw', { + months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split( + '_' + ), + monthsShort: + 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split( + '_' + ), + weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss: '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات', + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return arKw; + +}))); + + +/***/ }), + +/***/ 42353: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Libya) [ar-ly] +//! author : Ali Hmer: https://github.com/kikoanis + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '1', + 2: '2', + 3: '3', + 4: '4', + 5: '5', + 6: '6', + 7: '7', + 8: '8', + 9: '9', + 0: '0', + }, + pluralForm = function (n) { + return n === 0 + ? 0 + : n === 1 + ? 1 + : n === 2 + ? 2 + : n % 100 >= 3 && n % 100 <= 10 + ? 3 + : n % 100 >= 11 + ? 4 + : 5; + }, + plurals = { + s: [ + 'أقل من ثانية', + 'ثانية واحدة', + ['ثانيتان', 'ثانيتين'], + '%d ثوان', + '%d ثانية', + '%d ثانية', + ], + m: [ + 'أقل من دقيقة', + 'دقيقة واحدة', + ['دقيقتان', 'دقيقتين'], + '%d دقائق', + '%d دقيقة', + '%d دقيقة', + ], + h: [ + 'أقل من ساعة', + 'ساعة واحدة', + ['ساعتان', 'ساعتين'], + '%d ساعات', + '%d ساعة', + '%d ساعة', + ], + d: [ + 'أقل من يوم', + 'يوم واحد', + ['يومان', 'يومين'], + '%d أيام', + '%d يومًا', + '%d يوم', + ], + M: [ + 'أقل من شهر', + 'شهر واحد', + ['شهران', 'شهرين'], + '%d أشهر', + '%d شهرا', + '%d شهر', + ], + y: [ + 'أقل من عام', + 'عام واحد', + ['عامان', 'عامين'], + '%d أعوام', + '%d عامًا', + '%d عام', + ], + }, + pluralize = function (u) { + return function (number, withoutSuffix, string, isFuture) { + var f = pluralForm(number), + str = plurals[u][pluralForm(number)]; + if (f === 2) { + str = str[withoutSuffix ? 0 : 1]; + } + return str.replace(/%d/i, number); + }; + }, + months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', + ]; + + var arLy = moment.defineLocale('ar-ly', { + months: months, + monthsShort: months, + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'D/\u200FM/\u200FYYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ص|م/, + isPM: function (input) { + return 'م' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar: { + sameDay: '[اليوم عند الساعة] LT', + nextDay: '[غدًا عند الساعة] LT', + nextWeek: 'dddd [عند الساعة] LT', + lastDay: '[أمس عند الساعة] LT', + lastWeek: 'dddd [عند الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'بعد %s', + past: 'منذ %s', + s: pluralize('s'), + ss: pluralize('s'), + m: pluralize('m'), + mm: pluralize('m'), + h: pluralize('h'), + hh: pluralize('h'), + d: pluralize('d'), + dd: pluralize('d'), + M: pluralize('M'), + MM: pluralize('M'), + y: pluralize('y'), + yy: pluralize('y'), + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return arLy; + +}))); + + +/***/ }), + +/***/ 24496: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Morocco) [ar-ma] +//! author : ElFadili Yassine : https://github.com/ElFadiliY +//! author : Abdel Said : https://github.com/abdelsaid + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var arMa = moment.defineLocale('ar-ma', { + months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split( + '_' + ), + monthsShort: + 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split( + '_' + ), + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss: '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return arMa; + +}))); + + +/***/ }), + +/***/ 6947: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Palestine) [ar-ps] +//! author : Majd Al-Shihabi : https://github.com/majdal + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '١', + 2: '٢', + 3: '٣', + 4: '٤', + 5: '٥', + 6: '٦', + 7: '٧', + 8: '٨', + 9: '٩', + 0: '٠', + }, + numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0', + }; + + var arPs = moment.defineLocale('ar-ps', { + months: 'كانون الثاني_شباط_آذار_نيسان_أيّار_حزيران_تمّوز_آب_أيلول_تشري الأوّل_تشرين الثاني_كانون الأوّل'.split( + '_' + ), + monthsShort: + 'ك٢_شباط_آذار_نيسان_أيّار_حزيران_تمّوز_آب_أيلول_ت١_ت٢_ك١'.split('_'), + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ص|م/, + isPM: function (input) { + return 'م' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss: '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات', + }, + preparse: function (string) { + return string + .replace(/[٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }) + .split('') // reversed since negative lookbehind not supported everywhere + .reverse() + .join('') + .replace(/[١٢](?![\u062a\u0643])/g, function (match) { + return numberMap[match]; + }) + .split('') + .reverse() + .join('') + .replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return arPs; + +}))); + + +/***/ }), + +/***/ 60301: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Saudi Arabia) [ar-sa] +//! author : Suhail Alkowaileet : https://github.com/xsoh + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '١', + 2: '٢', + 3: '٣', + 4: '٤', + 5: '٥', + 6: '٦', + 7: '٧', + 8: '٨', + 9: '٩', + 0: '٠', + }, + numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0', + }; + + var arSa = moment.defineLocale('ar-sa', { + months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split( + '_' + ), + monthsShort: + 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split( + '_' + ), + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ص|م/, + isPM: function (input) { + return 'م' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss: '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات', + }, + preparse: function (string) { + return string + .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }) + .replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return arSa; + +}))); + + +/***/ }), + +/***/ 89756: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic (Tunisia) [ar-tn] +//! author : Nader Toukabri : https://github.com/naderio + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var arTn = moment.defineLocale('ar-tn', { + months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split( + '_' + ), + monthsShort: + 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split( + '_' + ), + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss: '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return arTn; + +}))); + + +/***/ }), + +/***/ 61509: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Arabic [ar] +//! author : Abdel Said: https://github.com/abdelsaid +//! author : Ahmed Elkhatib +//! author : forabi https://github.com/forabi + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '١', + 2: '٢', + 3: '٣', + 4: '٤', + 5: '٥', + 6: '٦', + 7: '٧', + 8: '٨', + 9: '٩', + 0: '٠', + }, + numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0', + }, + pluralForm = function (n) { + return n === 0 + ? 0 + : n === 1 + ? 1 + : n === 2 + ? 2 + : n % 100 >= 3 && n % 100 <= 10 + ? 3 + : n % 100 >= 11 + ? 4 + : 5; + }, + plurals = { + s: [ + 'أقل من ثانية', + 'ثانية واحدة', + ['ثانيتان', 'ثانيتين'], + '%d ثوان', + '%d ثانية', + '%d ثانية', + ], + m: [ + 'أقل من دقيقة', + 'دقيقة واحدة', + ['دقيقتان', 'دقيقتين'], + '%d دقائق', + '%d دقيقة', + '%d دقيقة', + ], + h: [ + 'أقل من ساعة', + 'ساعة واحدة', + ['ساعتان', 'ساعتين'], + '%d ساعات', + '%d ساعة', + '%d ساعة', + ], + d: [ + 'أقل من يوم', + 'يوم واحد', + ['يومان', 'يومين'], + '%d أيام', + '%d يومًا', + '%d يوم', + ], + M: [ + 'أقل من شهر', + 'شهر واحد', + ['شهران', 'شهرين'], + '%d أشهر', + '%d شهرا', + '%d شهر', + ], + y: [ + 'أقل من عام', + 'عام واحد', + ['عامان', 'عامين'], + '%d أعوام', + '%d عامًا', + '%d عام', + ], + }, + pluralize = function (u) { + return function (number, withoutSuffix, string, isFuture) { + var f = pluralForm(number), + str = plurals[u][pluralForm(number)]; + if (f === 2) { + str = str[withoutSuffix ? 0 : 1]; + } + return str.replace(/%d/i, number); + }; + }, + months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر', + ]; + + var ar = moment.defineLocale('ar', { + months: months, + monthsShort: months, + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'D/\u200FM/\u200FYYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ص|م/, + isPM: function (input) { + return 'م' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar: { + sameDay: '[اليوم عند الساعة] LT', + nextDay: '[غدًا عند الساعة] LT', + nextWeek: 'dddd [عند الساعة] LT', + lastDay: '[أمس عند الساعة] LT', + lastWeek: 'dddd [عند الساعة] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'بعد %s', + past: 'منذ %s', + s: pluralize('s'), + ss: pluralize('s'), + m: pluralize('m'), + mm: pluralize('m'), + h: pluralize('h'), + hh: pluralize('h'), + d: pluralize('d'), + dd: pluralize('d'), + M: pluralize('M'), + MM: pluralize('M'), + y: pluralize('y'), + yy: pluralize('y'), + }, + preparse: function (string) { + return string + .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }) + .replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return ar; + +}))); + + +/***/ }), + +/***/ 95533: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Azerbaijani [az] +//! author : topchiyev : https://github.com/topchiyev + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 1: '-inci', + 5: '-inci', + 8: '-inci', + 70: '-inci', + 80: '-inci', + 2: '-nci', + 7: '-nci', + 20: '-nci', + 50: '-nci', + 3: '-üncü', + 4: '-üncü', + 100: '-üncü', + 6: '-ncı', + 9: '-uncu', + 10: '-uncu', + 30: '-uncu', + 60: '-ıncı', + 90: '-ıncı', + }; + + var az = moment.defineLocale('az', { + months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split( + '_' + ), + monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), + weekdays: + 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split( + '_' + ), + weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), + weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[bugün saat] LT', + nextDay: '[sabah saat] LT', + nextWeek: '[gələn həftə] dddd [saat] LT', + lastDay: '[dünən] LT', + lastWeek: '[keçən həftə] dddd [saat] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s sonra', + past: '%s əvvəl', + s: 'bir neçə saniyə', + ss: '%d saniyə', + m: 'bir dəqiqə', + mm: '%d dəqiqə', + h: 'bir saat', + hh: '%d saat', + d: 'bir gün', + dd: '%d gün', + M: 'bir ay', + MM: '%d ay', + y: 'bir il', + yy: '%d il', + }, + meridiemParse: /gecə|səhər|gündüz|axşam/, + isPM: function (input) { + return /^(gündüz|axşam)$/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'gecə'; + } else if (hour < 12) { + return 'səhər'; + } else if (hour < 17) { + return 'gündüz'; + } else { + return 'axşam'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, + ordinal: function (number) { + if (number === 0) { + // special case for zero + return number + '-ıncı'; + } + var a = number % 10, + b = (number % 100) - a, + c = number >= 100 ? 100 : null; + return number + (suffixes[a] || suffixes[b] || suffixes[c]); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return az; + +}))); + + +/***/ }), + +/***/ 28959: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Belarusian [be] +//! author : Dmitry Demidov : https://github.com/demidov91 +//! author: Praleska: http://praleska.pro/ +//! Author : Menelion Elensúle : https://github.com/Oire + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 + ? forms[0] + : num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) + ? forms[1] + : forms[2]; + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + ss: withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', + mm: withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', + hh: withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', + dd: 'дзень_дні_дзён', + MM: 'месяц_месяцы_месяцаў', + yy: 'год_гады_гадоў', + }; + if (key === 'm') { + return withoutSuffix ? 'хвіліна' : 'хвіліну'; + } else if (key === 'h') { + return withoutSuffix ? 'гадзіна' : 'гадзіну'; + } else { + return number + ' ' + plural(format[key], +number); + } + } + + var be = moment.defineLocale('be', { + months: { + format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split( + '_' + ), + standalone: + 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split( + '_' + ), + }, + monthsShort: + 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), + weekdays: { + format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split( + '_' + ), + standalone: + 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split( + '_' + ), + isFormat: /\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/, + }, + weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), + weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY г.', + LLL: 'D MMMM YYYY г., HH:mm', + LLLL: 'dddd, D MMMM YYYY г., HH:mm', + }, + calendar: { + sameDay: '[Сёння ў] LT', + nextDay: '[Заўтра ў] LT', + lastDay: '[Учора ў] LT', + nextWeek: function () { + return '[У] dddd [ў] LT'; + }, + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 5: + case 6: + return '[У мінулую] dddd [ў] LT'; + case 1: + case 2: + case 4: + return '[У мінулы] dddd [ў] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'праз %s', + past: '%s таму', + s: 'некалькі секунд', + m: relativeTimeWithPlural, + mm: relativeTimeWithPlural, + h: relativeTimeWithPlural, + hh: relativeTimeWithPlural, + d: 'дзень', + dd: relativeTimeWithPlural, + M: 'месяц', + MM: relativeTimeWithPlural, + y: 'год', + yy: relativeTimeWithPlural, + }, + meridiemParse: /ночы|раніцы|дня|вечара/, + isPM: function (input) { + return /^(дня|вечара)$/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'ночы'; + } else if (hour < 12) { + return 'раніцы'; + } else if (hour < 17) { + return 'дня'; + } else { + return 'вечара'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return (number % 10 === 2 || number % 10 === 3) && + number % 100 !== 12 && + number % 100 !== 13 + ? number + '-і' + : number + '-ы'; + case 'D': + return number + '-га'; + default: + return number; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return be; + +}))); + + +/***/ }), + +/***/ 47777: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Bulgarian [bg] +//! author : Krasen Borisov : https://github.com/kraz + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var bg = moment.defineLocale('bg', { + months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split( + '_' + ), + monthsShort: 'яну_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), + weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split( + '_' + ), + weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'), + weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'D.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY H:mm', + LLLL: 'dddd, D MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[Днес в] LT', + nextDay: '[Утре в] LT', + nextWeek: 'dddd [в] LT', + lastDay: '[Вчера в] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 6: + return '[Миналата] dddd [в] LT'; + case 1: + case 2: + case 4: + case 5: + return '[Миналия] dddd [в] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'след %s', + past: 'преди %s', + s: 'няколко секунди', + ss: '%d секунди', + m: 'минута', + mm: '%d минути', + h: 'час', + hh: '%d часа', + d: 'ден', + dd: '%d дена', + w: 'седмица', + ww: '%d седмици', + M: 'месец', + MM: '%d месеца', + y: 'година', + yy: '%d години', + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, + ordinal: function (number) { + var lastDigit = number % 10, + last2Digits = number % 100; + if (number === 0) { + return number + '-ев'; + } else if (last2Digits === 0) { + return number + '-ен'; + } else if (last2Digits > 10 && last2Digits < 20) { + return number + '-ти'; + } else if (lastDigit === 1) { + return number + '-ви'; + } else if (lastDigit === 2) { + return number + '-ри'; + } else if (lastDigit === 7 || lastDigit === 8) { + return number + '-ми'; + } else { + return number + '-ти'; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return bg; + +}))); + + +/***/ }), + +/***/ 54903: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Bambara [bm] +//! author : Estelle Comment : https://github.com/estellecomment + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var bm = moment.defineLocale('bm', { + months: 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split( + '_' + ), + monthsShort: 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'), + weekdays: 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'), + weekdaysShort: 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'), + weekdaysMin: 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'MMMM [tile] D [san] YYYY', + LLL: 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', + LLLL: 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', + }, + calendar: { + sameDay: '[Bi lɛrɛ] LT', + nextDay: '[Sini lɛrɛ] LT', + nextWeek: 'dddd [don lɛrɛ] LT', + lastDay: '[Kunu lɛrɛ] LT', + lastWeek: 'dddd [tɛmɛnen lɛrɛ] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s kɔnɔ', + past: 'a bɛ %s bɔ', + s: 'sanga dama dama', + ss: 'sekondi %d', + m: 'miniti kelen', + mm: 'miniti %d', + h: 'lɛrɛ kelen', + hh: 'lɛrɛ %d', + d: 'tile kelen', + dd: 'tile %d', + M: 'kalo kelen', + MM: 'kalo %d', + y: 'san kelen', + yy: 'san %d', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return bm; + +}))); + + +/***/ }), + +/***/ 17357: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Bengali (Bangladesh) [bn-bd] +//! author : Asraf Hossain Patoary : https://github.com/ashwoolford + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '১', + 2: '২', + 3: '৩', + 4: '৪', + 5: '৫', + 6: '৬', + 7: '৭', + 8: '৮', + 9: '৯', + 0: '০', + }, + numberMap = { + '১': '1', + '২': '2', + '৩': '3', + '৪': '4', + '৫': '5', + '৬': '6', + '৭': '7', + '৮': '8', + '৯': '9', + '০': '0', + }; + + var bnBd = moment.defineLocale('bn-bd', { + months: 'জানুয়ারি_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split( + '_' + ), + monthsShort: + 'জানু_ফেব্রু_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্ট_অক্টো_নভে_ডিসে'.split( + '_' + ), + weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split( + '_' + ), + weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), + weekdaysMin: 'রবি_সোম_মঙ্গল_বুধ_বৃহ_শুক্র_শনি'.split('_'), + longDateFormat: { + LT: 'A h:mm সময়', + LTS: 'A h:mm:ss সময়', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm সময়', + LLLL: 'dddd, D MMMM YYYY, A h:mm সময়', + }, + calendar: { + sameDay: '[আজ] LT', + nextDay: '[আগামীকাল] LT', + nextWeek: 'dddd, LT', + lastDay: '[গতকাল] LT', + lastWeek: '[গত] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s পরে', + past: '%s আগে', + s: 'কয়েক সেকেন্ড', + ss: '%d সেকেন্ড', + m: 'এক মিনিট', + mm: '%d মিনিট', + h: 'এক ঘন্টা', + hh: '%d ঘন্টা', + d: 'এক দিন', + dd: '%d দিন', + M: 'এক মাস', + MM: '%d মাস', + y: 'এক বছর', + yy: '%d বছর', + }, + preparse: function (string) { + return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + + meridiemParse: /রাত|ভোর|সকাল|দুপুর|বিকাল|সন্ধ্যা|রাত/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'রাত') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ভোর') { + return hour; + } else if (meridiem === 'সকাল') { + return hour; + } else if (meridiem === 'দুপুর') { + return hour >= 3 ? hour : hour + 12; + } else if (meridiem === 'বিকাল') { + return hour + 12; + } else if (meridiem === 'সন্ধ্যা') { + return hour + 12; + } + }, + + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'রাত'; + } else if (hour < 6) { + return 'ভোর'; + } else if (hour < 12) { + return 'সকাল'; + } else if (hour < 15) { + return 'দুপুর'; + } else if (hour < 18) { + return 'বিকাল'; + } else if (hour < 20) { + return 'সন্ধ্যা'; + } else { + return 'রাত'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return bnBd; + +}))); + + +/***/ }), + +/***/ 61290: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Bengali [bn] +//! author : Kaushik Gandhi : https://github.com/kaushikgandhi + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '১', + 2: '২', + 3: '৩', + 4: '৪', + 5: '৫', + 6: '৬', + 7: '৭', + 8: '৮', + 9: '৯', + 0: '০', + }, + numberMap = { + '১': '1', + '২': '2', + '৩': '3', + '৪': '4', + '৫': '5', + '৬': '6', + '৭': '7', + '৮': '8', + '৯': '9', + '০': '0', + }; + + var bn = moment.defineLocale('bn', { + months: 'জানুয়ারি_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split( + '_' + ), + monthsShort: + 'জানু_ফেব্রু_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্ট_অক্টো_নভে_ডিসে'.split( + '_' + ), + weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split( + '_' + ), + weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), + weekdaysMin: 'রবি_সোম_মঙ্গল_বুধ_বৃহ_শুক্র_শনি'.split('_'), + longDateFormat: { + LT: 'A h:mm সময়', + LTS: 'A h:mm:ss সময়', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm সময়', + LLLL: 'dddd, D MMMM YYYY, A h:mm সময়', + }, + calendar: { + sameDay: '[আজ] LT', + nextDay: '[আগামীকাল] LT', + nextWeek: 'dddd, LT', + lastDay: '[গতকাল] LT', + lastWeek: '[গত] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s পরে', + past: '%s আগে', + s: 'কয়েক সেকেন্ড', + ss: '%d সেকেন্ড', + m: 'এক মিনিট', + mm: '%d মিনিট', + h: 'এক ঘন্টা', + hh: '%d ঘন্টা', + d: 'এক দিন', + dd: '%d দিন', + M: 'এক মাস', + MM: '%d মাস', + y: 'এক বছর', + yy: '%d বছর', + }, + preparse: function (string) { + return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ( + (meridiem === 'রাত' && hour >= 4) || + (meridiem === 'দুপুর' && hour < 5) || + meridiem === 'বিকাল' + ) { + return hour + 12; + } else { + return hour; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'রাত'; + } else if (hour < 10) { + return 'সকাল'; + } else if (hour < 17) { + return 'দুপুর'; + } else if (hour < 20) { + return 'বিকাল'; + } else { + return 'রাত'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return bn; + +}))); + + +/***/ }), + +/***/ 31545: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Tibetan [bo] +//! author : Thupten N. Chakrishar : https://github.com/vajradog + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '༡', + 2: '༢', + 3: '༣', + 4: '༤', + 5: '༥', + 6: '༦', + 7: '༧', + 8: '༨', + 9: '༩', + 0: '༠', + }, + numberMap = { + '༡': '1', + '༢': '2', + '༣': '3', + '༤': '4', + '༥': '5', + '༦': '6', + '༧': '7', + '༨': '8', + '༩': '9', + '༠': '0', + }; + + var bo = moment.defineLocale('bo', { + months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split( + '_' + ), + monthsShort: + 'ཟླ་1_ཟླ་2_ཟླ་3_ཟླ་4_ཟླ་5_ཟླ་6_ཟླ་7_ཟླ་8_ཟླ་9_ཟླ་10_ཟླ་11_ཟླ་12'.split( + '_' + ), + monthsShortRegex: /^(ཟླ་\d{1,2})/, + monthsParseExact: true, + weekdays: + 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split( + '_' + ), + weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split( + '_' + ), + weekdaysMin: 'ཉི_ཟླ_མིག_ལྷག_ཕུར_སངས_སྤེན'.split('_'), + longDateFormat: { + LT: 'A h:mm', + LTS: 'A h:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm', + LLLL: 'dddd, D MMMM YYYY, A h:mm', + }, + calendar: { + sameDay: '[དི་རིང] LT', + nextDay: '[སང་ཉིན] LT', + nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT', + lastDay: '[ཁ་སང] LT', + lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s ལ་', + past: '%s སྔན་ལ', + s: 'ལམ་སང', + ss: '%d སྐར་ཆ།', + m: 'སྐར་མ་གཅིག', + mm: '%d སྐར་མ', + h: 'ཆུ་ཚོད་གཅིག', + hh: '%d ཆུ་ཚོད', + d: 'ཉིན་གཅིག', + dd: '%d ཉིན་', + M: 'ཟླ་བ་གཅིག', + MM: '%d ཟླ་བ', + y: 'ལོ་གཅིག', + yy: '%d ལོ', + }, + preparse: function (string) { + return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ( + (meridiem === 'མཚན་མོ' && hour >= 4) || + (meridiem === 'ཉིན་གུང' && hour < 5) || + meridiem === 'དགོང་དག' + ) { + return hour + 12; + } else { + return hour; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'མཚན་མོ'; + } else if (hour < 10) { + return 'ཞོགས་ཀས'; + } else if (hour < 17) { + return 'ཉིན་གུང'; + } else if (hour < 20) { + return 'དགོང་དག'; + } else { + return 'མཚན་མོ'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return bo; + +}))); + + +/***/ }), + +/***/ 11470: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Breton [br] +//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function relativeTimeWithMutation(number, withoutSuffix, key) { + var format = { + mm: 'munutenn', + MM: 'miz', + dd: 'devezh', + }; + return number + ' ' + mutation(format[key], number); + } + function specialMutationForYears(number) { + switch (lastNumber(number)) { + case 1: + case 3: + case 4: + case 5: + case 9: + return number + ' bloaz'; + default: + return number + ' vloaz'; + } + } + function lastNumber(number) { + if (number > 9) { + return lastNumber(number % 10); + } + return number; + } + function mutation(text, number) { + if (number === 2) { + return softMutation(text); + } + return text; + } + function softMutation(text) { + var mutationTable = { + m: 'v', + b: 'v', + d: 'z', + }; + if (mutationTable[text.charAt(0)] === undefined) { + return text; + } + return mutationTable[text.charAt(0)] + text.substring(1); + } + + var monthsParse = [ + /^gen/i, + /^c[ʼ\']hwe/i, + /^meu/i, + /^ebr/i, + /^mae/i, + /^(mez|eve)/i, + /^gou/i, + /^eos/i, + /^gwe/i, + /^her/i, + /^du/i, + /^ker/i, + ], + monthsRegex = + /^(genver|c[ʼ\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu|gen|c[ʼ\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i, + monthsStrictRegex = + /^(genver|c[ʼ\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu)/i, + monthsShortStrictRegex = + /^(gen|c[ʼ\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i, + fullWeekdaysParse = [ + /^sul/i, + /^lun/i, + /^meurzh/i, + /^merc[ʼ\']her/i, + /^yaou/i, + /^gwener/i, + /^sadorn/i, + ], + shortWeekdaysParse = [ + /^Sul/i, + /^Lun/i, + /^Meu/i, + /^Mer/i, + /^Yao/i, + /^Gwe/i, + /^Sad/i, + ], + minWeekdaysParse = [ + /^Su/i, + /^Lu/i, + /^Me([^r]|$)/i, + /^Mer/i, + /^Ya/i, + /^Gw/i, + /^Sa/i, + ]; + + var br = moment.defineLocale('br', { + months: 'Genver_Cʼhwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split( + '_' + ), + monthsShort: 'Gen_Cʼhwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), + weekdays: 'Sul_Lun_Meurzh_Mercʼher_Yaou_Gwener_Sadorn'.split('_'), + weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), + weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), + weekdaysParse: minWeekdaysParse, + fullWeekdaysParse: fullWeekdaysParse, + shortWeekdaysParse: shortWeekdaysParse, + minWeekdaysParse: minWeekdaysParse, + + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: monthsStrictRegex, + monthsShortStrictRegex: monthsShortStrictRegex, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [a viz] MMMM YYYY', + LLL: 'D [a viz] MMMM YYYY HH:mm', + LLLL: 'dddd, D [a viz] MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Hiziv da] LT', + nextDay: '[Warcʼhoazh da] LT', + nextWeek: 'dddd [da] LT', + lastDay: '[Decʼh da] LT', + lastWeek: 'dddd [paset da] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'a-benn %s', + past: '%s ʼzo', + s: 'un nebeud segondennoù', + ss: '%d eilenn', + m: 'ur vunutenn', + mm: relativeTimeWithMutation, + h: 'un eur', + hh: '%d eur', + d: 'un devezh', + dd: relativeTimeWithMutation, + M: 'ur miz', + MM: relativeTimeWithMutation, + y: 'ur bloaz', + yy: specialMutationForYears, + }, + dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/, + ordinal: function (number) { + var output = number === 1 ? 'añ' : 'vet'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + meridiemParse: /a.m.|g.m./, // goude merenn | a-raok merenn + isPM: function (token) { + return token === 'g.m.'; + }, + meridiem: function (hour, minute, isLower) { + return hour < 12 ? 'a.m.' : 'g.m.'; + }, + }); + + return br; + +}))); + + +/***/ }), + +/***/ 44429: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Bosnian [bs] +//! author : Nedim Cholich : https://github.com/frontyard +//! author : Rasid Redzic : https://github.com/rasidre +//! based on (hr) translation by Bojan Marković + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + switch (key) { + case 'm': + return withoutSuffix + ? 'jedna minuta' + : isFuture + ? 'jednu minutu' + : 'jedne minute'; + } + } + + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + if (number === 1) { + result += 'sekunda'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sekunde'; + } else { + result += 'sekundi'; + } + return result; + case 'mm': + if (number === 1) { + result += 'minuta'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'minute'; + } else { + result += 'minuta'; + } + return result; + case 'h': + return withoutSuffix ? 'jedan sat' : 'jedan sat'; + case 'hh': + if (number === 1) { + result += 'sat'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sata'; + } else { + result += 'sati'; + } + return result; + case 'dd': + if (number === 1) { + result += 'dan'; + } else { + result += 'dana'; + } + return result; + case 'MM': + if (number === 1) { + result += 'mjesec'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'mjeseca'; + } else { + result += 'mjeseci'; + } + return result; + case 'yy': + if (number === 1) { + result += 'godina'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'godine'; + } else { + result += 'godina'; + } + return result; + } + } + + var bs = moment.defineLocale('bs', { + months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split( + '_' + ), + monthsShort: + 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split( + '_' + ), + weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[danas u] LT', + nextDay: '[sutra u] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay: '[jučer u] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + return '[prošlu] dddd [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prošli] dddd [u] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'prije %s', + s: 'par sekundi', + ss: translate, + m: processRelativeTime, + mm: translate, + h: translate, + hh: translate, + d: 'dan', + dd: translate, + M: 'mjesec', + MM: translate, + y: 'godinu', + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return bs; + +}))); + + +/***/ }), + +/***/ 7306: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Catalan [ca] +//! author : Juan G. Hurtado : https://github.com/juanghurtado + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ca = moment.defineLocale('ca', { + months: { + standalone: + 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split( + '_' + ), + format: "de gener_de febrer_de març_d'abril_de maig_de juny_de juliol_d'agost_de setembre_d'octubre_de novembre_de desembre".split( + '_' + ), + isFormat: /D[oD]?(\s)+MMMM/, + }, + monthsShort: + 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split( + '_' + ), + weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), + weekdaysMin: 'dg_dl_dt_dc_dj_dv_ds'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM [de] YYYY', + ll: 'D MMM YYYY', + LLL: 'D MMMM [de] YYYY [a les] H:mm', + lll: 'D MMM YYYY, H:mm', + LLLL: 'dddd D MMMM [de] YYYY [a les] H:mm', + llll: 'ddd D MMM YYYY, H:mm', + }, + calendar: { + sameDay: function () { + return '[avui a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; + }, + nextDay: function () { + return '[demà a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; + }, + nextWeek: function () { + return 'dddd [a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; + }, + lastDay: function () { + return '[ahir a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT'; + }, + lastWeek: function () { + return ( + '[el] dddd [passat a ' + + (this.hours() !== 1 ? 'les' : 'la') + + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: "d'aquí %s", + past: 'fa %s', + s: 'uns segons', + ss: '%d segons', + m: 'un minut', + mm: '%d minuts', + h: 'una hora', + hh: '%d hores', + d: 'un dia', + dd: '%d dies', + M: 'un mes', + MM: '%d mesos', + y: 'un any', + yy: '%d anys', + }, + dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, + ordinal: function (number, period) { + var output = + number === 1 + ? 'r' + : number === 2 + ? 'n' + : number === 3 + ? 'r' + : number === 4 + ? 't' + : 'è'; + if (period === 'w' || period === 'W') { + output = 'a'; + } + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return ca; + +}))); + + +/***/ }), + +/***/ 56464: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Czech [cs] +//! author : petrbela : https://github.com/petrbela + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = { + standalone: + 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split( + '_' + ), + format: 'ledna_února_března_dubna_května_června_července_srpna_září_října_listopadu_prosince'.split( + '_' + ), + isFormat: /DD?[o.]?(\[[^\[\]]*\]|\s)+MMMM/, + }, + monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'), + monthsParse = [ + /^led/i, + /^úno/i, + /^bře/i, + /^dub/i, + /^kvě/i, + /^(čvn|červen$|června)/i, + /^(čvc|červenec|července)/i, + /^srp/i, + /^zář/i, + /^říj/i, + /^lis/i, + /^pro/i, + ], + // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. + // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. + monthsRegex = + /^(leden|únor|březen|duben|květen|červenec|července|červen|června|srpen|září|říjen|listopad|prosinec|led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i; + + function plural(n) { + return n > 1 && n < 5 && ~~(n / 10) !== 1; + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': // a few seconds / in a few seconds / a few seconds ago + return withoutSuffix || isFuture ? 'pár sekund' : 'pár sekundami'; + case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'sekundy' : 'sekund'); + } else { + return result + 'sekundami'; + } + case 'm': // a minute / in a minute / a minute ago + return withoutSuffix ? 'minuta' : isFuture ? 'minutu' : 'minutou'; + case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'minuty' : 'minut'); + } else { + return result + 'minutami'; + } + case 'h': // an hour / in an hour / an hour ago + return withoutSuffix ? 'hodina' : isFuture ? 'hodinu' : 'hodinou'; + case 'hh': // 9 hours / in 9 hours / 9 hours ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'hodiny' : 'hodin'); + } else { + return result + 'hodinami'; + } + case 'd': // a day / in a day / a day ago + return withoutSuffix || isFuture ? 'den' : 'dnem'; + case 'dd': // 9 days / in 9 days / 9 days ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'dny' : 'dní'); + } else { + return result + 'dny'; + } + case 'M': // a month / in a month / a month ago + return withoutSuffix || isFuture ? 'měsíc' : 'měsícem'; + case 'MM': // 9 months / in 9 months / 9 months ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'měsíce' : 'měsíců'); + } else { + return result + 'měsíci'; + } + case 'y': // a year / in a year / a year ago + return withoutSuffix || isFuture ? 'rok' : 'rokem'; + case 'yy': // 9 years / in 9 years / 9 years ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'roky' : 'let'); + } else { + return result + 'lety'; + } + } + } + + var cs = moment.defineLocale('cs', { + months: months, + monthsShort: monthsShort, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. + // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. + monthsStrictRegex: + /^(leden|ledna|února|únor|březen|března|duben|dubna|květen|května|červenec|července|červen|června|srpen|srpna|září|říjen|října|listopadu|listopad|prosinec|prosince)/i, + monthsShortStrictRegex: + /^(led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), + weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'), + weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd D. MMMM YYYY H:mm', + l: 'D. M. YYYY', + }, + calendar: { + sameDay: '[dnes v] LT', + nextDay: '[zítra v] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[v neděli v] LT'; + case 1: + case 2: + return '[v] dddd [v] LT'; + case 3: + return '[ve středu v] LT'; + case 4: + return '[ve čtvrtek v] LT'; + case 5: + return '[v pátek v] LT'; + case 6: + return '[v sobotu v] LT'; + } + }, + lastDay: '[včera v] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[minulou neděli v] LT'; + case 1: + case 2: + return '[minulé] dddd [v] LT'; + case 3: + return '[minulou středu v] LT'; + case 4: + case 5: + return '[minulý] dddd [v] LT'; + case 6: + return '[minulou sobotu v] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'před %s', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return cs; + +}))); + + +/***/ }), + +/***/ 73635: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Chuvash [cv] +//! author : Anatoly Mironov : https://github.com/mirontoli + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var cv = moment.defineLocale('cv', { + months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split( + '_' + ), + monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), + weekdays: + 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split( + '_' + ), + weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), + weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD-MM-YYYY', + LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', + LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', + LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', + }, + calendar: { + sameDay: '[Паян] LT [сехетре]', + nextDay: '[Ыран] LT [сехетре]', + lastDay: '[Ӗнер] LT [сехетре]', + nextWeek: '[Ҫитес] dddd LT [сехетре]', + lastWeek: '[Иртнӗ] dddd LT [сехетре]', + sameElse: 'L', + }, + relativeTime: { + future: function (output) { + var affix = /сехет$/i.exec(output) + ? 'рен' + : /ҫул$/i.exec(output) + ? 'тан' + : 'ран'; + return output + affix; + }, + past: '%s каялла', + s: 'пӗр-ик ҫеккунт', + ss: '%d ҫеккунт', + m: 'пӗр минут', + mm: '%d минут', + h: 'пӗр сехет', + hh: '%d сехет', + d: 'пӗр кун', + dd: '%d кун', + M: 'пӗр уйӑх', + MM: '%d уйӑх', + y: 'пӗр ҫул', + yy: '%d ҫул', + }, + dayOfMonthOrdinalParse: /\d{1,2}-мӗш/, + ordinal: '%d-мӗш', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return cv; + +}))); + + +/***/ }), + +/***/ 64226: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Welsh [cy] +//! author : Robert Allen : https://github.com/robgallen +//! author : https://github.com/ryangreaves + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var cy = moment.defineLocale('cy', { + months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split( + '_' + ), + monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split( + '_' + ), + weekdays: + 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split( + '_' + ), + weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), + weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), + weekdaysParseExact: true, + // time formats are the same as en-gb + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Heddiw am] LT', + nextDay: '[Yfory am] LT', + nextWeek: 'dddd [am] LT', + lastDay: '[Ddoe am] LT', + lastWeek: 'dddd [diwethaf am] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'mewn %s', + past: '%s yn ôl', + s: 'ychydig eiliadau', + ss: '%d eiliad', + m: 'munud', + mm: '%d munud', + h: 'awr', + hh: '%d awr', + d: 'diwrnod', + dd: '%d diwrnod', + M: 'mis', + MM: '%d mis', + y: 'blwyddyn', + yy: '%d flynedd', + }, + dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, + // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh + ordinal: function (number) { + var b = number, + output = '', + lookup = [ + '', + 'af', + 'il', + 'ydd', + 'ydd', + 'ed', + 'ed', + 'ed', + 'fed', + 'fed', + 'fed', // 1af to 10fed + 'eg', + 'fed', + 'eg', + 'eg', + 'fed', + 'eg', + 'eg', + 'fed', + 'eg', + 'fed', // 11eg to 20fed + ]; + if (b > 20) { + if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { + output = 'fed'; // not 30ain, 70ain or 90ain + } else { + output = 'ain'; + } + } else if (b > 0) { + output = lookup[b]; + } + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return cy; + +}))); + + +/***/ }), + +/***/ 93601: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Danish [da] +//! author : Ulrik Nielsen : https://github.com/mrbase + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var da = moment.defineLocale('da', { + months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split( + '_' + ), + monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), + weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), + weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'), + weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY HH:mm', + LLLL: 'dddd [d.] D. MMMM YYYY [kl.] HH:mm', + }, + calendar: { + sameDay: '[i dag kl.] LT', + nextDay: '[i morgen kl.] LT', + nextWeek: 'på dddd [kl.] LT', + lastDay: '[i går kl.] LT', + lastWeek: '[i] dddd[s kl.] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'om %s', + past: '%s siden', + s: 'få sekunder', + ss: '%d sekunder', + m: 'et minut', + mm: '%d minutter', + h: 'en time', + hh: '%d timer', + d: 'en dag', + dd: '%d dage', + M: 'en måned', + MM: '%d måneder', + y: 'et år', + yy: '%d år', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return da; + +}))); + + +/***/ }), + +/***/ 26111: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : German (Austria) [de-at] +//! author : lluchs : https://github.com/lluchs +//! author: Menelion Elensúle: https://github.com/Oire +//! author : Martin Groller : https://github.com/MadMG +//! author : Mikolaj Dadela : https://github.com/mik01aj + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + m: ['eine Minute', 'einer Minute'], + h: ['eine Stunde', 'einer Stunde'], + d: ['ein Tag', 'einem Tag'], + dd: [number + ' Tage', number + ' Tagen'], + w: ['eine Woche', 'einer Woche'], + M: ['ein Monat', 'einem Monat'], + MM: [number + ' Monate', number + ' Monaten'], + y: ['ein Jahr', 'einem Jahr'], + yy: [number + ' Jahre', number + ' Jahren'], + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + + var deAt = moment.defineLocale('de-at', { + months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split( + '_' + ), + monthsShort: + 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact: true, + weekdays: + 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split( + '_' + ), + weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), + weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY HH:mm', + LLLL: 'dddd, D. MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]', + }, + relativeTime: { + future: 'in %s', + past: 'vor %s', + s: 'ein paar Sekunden', + ss: '%d Sekunden', + m: processRelativeTime, + mm: '%d Minuten', + h: processRelativeTime, + hh: '%d Stunden', + d: processRelativeTime, + dd: processRelativeTime, + w: processRelativeTime, + ww: '%d Wochen', + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return deAt; + +}))); + + +/***/ }), + +/***/ 54697: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : German (Switzerland) [de-ch] +//! author : sschueller : https://github.com/sschueller + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + m: ['eine Minute', 'einer Minute'], + h: ['eine Stunde', 'einer Stunde'], + d: ['ein Tag', 'einem Tag'], + dd: [number + ' Tage', number + ' Tagen'], + w: ['eine Woche', 'einer Woche'], + M: ['ein Monat', 'einem Monat'], + MM: [number + ' Monate', number + ' Monaten'], + y: ['ein Jahr', 'einem Jahr'], + yy: [number + ' Jahre', number + ' Jahren'], + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + + var deCh = moment.defineLocale('de-ch', { + months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split( + '_' + ), + monthsShort: + 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact: true, + weekdays: + 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split( + '_' + ), + weekdaysShort: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY HH:mm', + LLLL: 'dddd, D. MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]', + }, + relativeTime: { + future: 'in %s', + past: 'vor %s', + s: 'ein paar Sekunden', + ss: '%d Sekunden', + m: processRelativeTime, + mm: '%d Minuten', + h: processRelativeTime, + hh: '%d Stunden', + d: processRelativeTime, + dd: processRelativeTime, + w: processRelativeTime, + ww: '%d Wochen', + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return deCh; + +}))); + + +/***/ }), + +/***/ 77853: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : German [de] +//! author : lluchs : https://github.com/lluchs +//! author: Menelion Elensúle: https://github.com/Oire +//! author : Mikolaj Dadela : https://github.com/mik01aj + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + m: ['eine Minute', 'einer Minute'], + h: ['eine Stunde', 'einer Stunde'], + d: ['ein Tag', 'einem Tag'], + dd: [number + ' Tage', number + ' Tagen'], + w: ['eine Woche', 'einer Woche'], + M: ['ein Monat', 'einem Monat'], + MM: [number + ' Monate', number + ' Monaten'], + y: ['ein Jahr', 'einem Jahr'], + yy: [number + ' Jahre', number + ' Jahren'], + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + + var de = moment.defineLocale('de', { + months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split( + '_' + ), + monthsShort: + 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact: true, + weekdays: + 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split( + '_' + ), + weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), + weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY HH:mm', + LLLL: 'dddd, D. MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]', + }, + relativeTime: { + future: 'in %s', + past: 'vor %s', + s: 'ein paar Sekunden', + ss: '%d Sekunden', + m: processRelativeTime, + mm: '%d Minuten', + h: processRelativeTime, + hh: '%d Stunden', + d: processRelativeTime, + dd: processRelativeTime, + w: processRelativeTime, + ww: '%d Wochen', + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return de; + +}))); + + +/***/ }), + +/***/ 60708: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Maldivian [dv] +//! author : Jawish Hameed : https://github.com/jawish + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = [ + 'ޖެނުއަރީ', + 'ފެބްރުއަރީ', + 'މާރިޗު', + 'އޭޕްރީލު', + 'މޭ', + 'ޖޫން', + 'ޖުލައި', + 'އޯގަސްޓު', + 'ސެޕްޓެމްބަރު', + 'އޮކްޓޯބަރު', + 'ނޮވެމްބަރު', + 'ޑިސެމްބަރު', + ], + weekdays = [ + 'އާދިއްތަ', + 'ހޯމަ', + 'އަންގާރަ', + 'ބުދަ', + 'ބުރާސްފަތި', + 'ހުކުރު', + 'ހޮނިހިރު', + ]; + + var dv = moment.defineLocale('dv', { + months: months, + monthsShort: months, + weekdays: weekdays, + weekdaysShort: weekdays, + weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'D/M/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + meridiemParse: /މކ|މފ/, + isPM: function (input) { + return 'މފ' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'މކ'; + } else { + return 'މފ'; + } + }, + calendar: { + sameDay: '[މިއަދު] LT', + nextDay: '[މާދަމާ] LT', + nextWeek: 'dddd LT', + lastDay: '[އިއްޔެ] LT', + lastWeek: '[ފާއިތުވި] dddd LT', + sameElse: 'L', + }, + relativeTime: { + future: 'ތެރޭގައި %s', + past: 'ކުރިން %s', + s: 'ސިކުންތުކޮޅެއް', + ss: 'd% ސިކުންތު', + m: 'މިނިޓެއް', + mm: 'މިނިޓު %d', + h: 'ގަޑިއިރެއް', + hh: 'ގަޑިއިރު %d', + d: 'ދުވަހެއް', + dd: 'ދުވަސް %d', + M: 'މަހެއް', + MM: 'މަސް %d', + y: 'އަހަރެއް', + yy: 'އަހަރު %d', + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + dow: 7, // Sunday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return dv; + +}))); + + +/***/ }), + +/***/ 54691: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Greek [el] +//! author : Aggelos Karalias : https://github.com/mehiel + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function isFunction(input) { + return ( + (typeof Function !== 'undefined' && input instanceof Function) || + Object.prototype.toString.call(input) === '[object Function]' + ); + } + + var el = moment.defineLocale('el', { + monthsNominativeEl: + 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split( + '_' + ), + monthsGenitiveEl: + 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split( + '_' + ), + months: function (momentToFormat, format) { + if (!momentToFormat) { + return this._monthsNominativeEl; + } else if ( + typeof format === 'string' && + /D/.test(format.substring(0, format.indexOf('MMMM'))) + ) { + // if there is a day number before 'MMMM' + return this._monthsGenitiveEl[momentToFormat.month()]; + } else { + return this._monthsNominativeEl[momentToFormat.month()]; + } + }, + monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), + weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split( + '_' + ), + weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), + weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), + meridiem: function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'μμ' : 'ΜΜ'; + } else { + return isLower ? 'πμ' : 'ΠΜ'; + } + }, + isPM: function (input) { + return (input + '').toLowerCase()[0] === 'μ'; + }, + meridiemParse: /[ΠΜ]\.?Μ?\.?/i, + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendarEl: { + sameDay: '[Σήμερα {}] LT', + nextDay: '[Αύριο {}] LT', + nextWeek: 'dddd [{}] LT', + lastDay: '[Χθες {}] LT', + lastWeek: function () { + switch (this.day()) { + case 6: + return '[το προηγούμενο] dddd [{}] LT'; + default: + return '[την προηγούμενη] dddd [{}] LT'; + } + }, + sameElse: 'L', + }, + calendar: function (key, mom) { + var output = this._calendarEl[key], + hours = mom && mom.hours(); + if (isFunction(output)) { + output = output.apply(mom); + } + return output.replace('{}', hours % 12 === 1 ? 'στη' : 'στις'); + }, + relativeTime: { + future: 'σε %s', + past: '%s πριν', + s: 'λίγα δευτερόλεπτα', + ss: '%d δευτερόλεπτα', + m: 'ένα λεπτό', + mm: '%d λεπτά', + h: 'μία ώρα', + hh: '%d ώρες', + d: 'μία μέρα', + dd: '%d μέρες', + M: 'ένας μήνας', + MM: '%d μήνες', + y: 'ένας χρόνος', + yy: '%d χρόνια', + }, + dayOfMonthOrdinalParse: /\d{1,2}η/, + ordinal: '%dη', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4st is the first week of the year. + }, + }); + + return el; + +}))); + + +/***/ }), + +/***/ 53872: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (Australia) [en-au] +//! author : Jared Morse : https://github.com/jarcoal + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enAu = moment.defineLocale('en-au', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return enAu; + +}))); + + +/***/ }), + +/***/ 28298: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (Canada) [en-ca] +//! author : Jonathan Abourbih : https://github.com/jonbca + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enCa = moment.defineLocale('en-ca', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'YYYY-MM-DD', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY h:mm A', + LLLL: 'dddd, MMMM D, YYYY h:mm A', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + }); + + return enCa; + +}))); + + +/***/ }), + +/***/ 56195: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (United Kingdom) [en-gb] +//! author : Chris Gedrim : https://github.com/chrisgedrim + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enGb = moment.defineLocale('en-gb', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return enGb; + +}))); + + +/***/ }), + +/***/ 66584: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (Ireland) [en-ie] +//! author : Chris Cartlidge : https://github.com/chriscartlidge + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enIe = moment.defineLocale('en-ie', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return enIe; + +}))); + + +/***/ }), + +/***/ 65543: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (Israel) [en-il] +//! author : Chris Gedrim : https://github.com/chrisgedrim + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enIl = moment.defineLocale('en-il', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + }); + + return enIl; + +}))); + + +/***/ }), + +/***/ 9033: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (India) [en-in] +//! author : Jatin Agrawal : https://github.com/jatinag22 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enIn = moment.defineLocale('en-in', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 1st is the first week of the year. + }, + }); + + return enIn; + +}))); + + +/***/ }), + +/***/ 79402: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (New Zealand) [en-nz] +//! author : Luke McGregor : https://github.com/lukemcgregor + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enNz = moment.defineLocale('en-nz', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return enNz; + +}))); + + +/***/ }), + +/***/ 43004: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : English (Singapore) [en-sg] +//! author : Matthew Castrillon-Madrigal : https://github.com/techdimension + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var enSg = moment.defineLocale('en-sg', { + months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( + '_' + ), + weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return enSg; + +}))); + + +/***/ }), + +/***/ 32934: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Esperanto [eo] +//! author : Colin Dean : https://github.com/colindean +//! author : Mia Nordentoft Imperatori : https://github.com/miestasmia +//! comment : miestasmia corrected the translation by colindean +//! comment : Vivakvo corrected the translation by colindean and miestasmia + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var eo = moment.defineLocale('eo', { + months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split( + '_' + ), + monthsShort: 'jan_feb_mart_apr_maj_jun_jul_aŭg_sept_okt_nov_dec'.split('_'), + weekdays: 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'), + weekdaysShort: 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'), + weekdaysMin: 'di_lu_ma_me_ĵa_ve_sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: '[la] D[-an de] MMMM, YYYY', + LLL: '[la] D[-an de] MMMM, YYYY HH:mm', + LLLL: 'dddd[n], [la] D[-an de] MMMM, YYYY HH:mm', + llll: 'ddd, [la] D[-an de] MMM, YYYY HH:mm', + }, + meridiemParse: /[ap]\.t\.m/i, + isPM: function (input) { + return input.charAt(0).toLowerCase() === 'p'; + }, + meridiem: function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'p.t.m.' : 'P.T.M.'; + } else { + return isLower ? 'a.t.m.' : 'A.T.M.'; + } + }, + calendar: { + sameDay: '[Hodiaŭ je] LT', + nextDay: '[Morgaŭ je] LT', + nextWeek: 'dddd[n je] LT', + lastDay: '[Hieraŭ je] LT', + lastWeek: '[pasintan] dddd[n je] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'post %s', + past: 'antaŭ %s', + s: 'kelkaj sekundoj', + ss: '%d sekundoj', + m: 'unu minuto', + mm: '%d minutoj', + h: 'unu horo', + hh: '%d horoj', + d: 'unu tago', //ne 'diurno', ĉar estas uzita por proksimumo + dd: '%d tagoj', + M: 'unu monato', + MM: '%d monatoj', + y: 'unu jaro', + yy: '%d jaroj', + }, + dayOfMonthOrdinalParse: /\d{1,2}a/, + ordinal: '%da', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return eo; + +}))); + + +/***/ }), + +/***/ 20838: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Spanish (Dominican Republic) [es-do] + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortDot = + 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split( + '_' + ), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'), + monthsParse = [ + /^ene/i, + /^feb/i, + /^mar/i, + /^abr/i, + /^may/i, + /^jun/i, + /^jul/i, + /^ago/i, + /^sep/i, + /^oct/i, + /^nov/i, + /^dic/i, + ], + monthsRegex = + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var esDo = moment.defineLocale('es-do', { + months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: + /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY h:mm A', + LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A', + }, + calendar: { + sameDay: function () { + return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextDay: function () { + return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextWeek: function () { + return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastDay: function () { + return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastWeek: function () { + return ( + '[el] dddd [pasado a la' + + (this.hours() !== 1 ? 's' : '') + + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: 'en %s', + past: 'hace %s', + s: 'unos segundos', + ss: '%d segundos', + m: 'un minuto', + mm: '%d minutos', + h: 'una hora', + hh: '%d horas', + d: 'un día', + dd: '%d días', + w: 'una semana', + ww: '%d semanas', + M: 'un mes', + MM: '%d meses', + y: 'un año', + yy: '%d años', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return esDo; + +}))); + + +/***/ }), + +/***/ 17730: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Spanish (Mexico) [es-mx] +//! author : JC Franco : https://github.com/jcfranco + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortDot = + 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split( + '_' + ), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'), + monthsParse = [ + /^ene/i, + /^feb/i, + /^mar/i, + /^abr/i, + /^may/i, + /^jun/i, + /^jul/i, + /^ago/i, + /^sep/i, + /^oct/i, + /^nov/i, + /^dic/i, + ], + monthsRegex = + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var esMx = moment.defineLocale('es-mx', { + months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: + /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY H:mm', + LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm', + }, + calendar: { + sameDay: function () { + return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextDay: function () { + return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextWeek: function () { + return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastDay: function () { + return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastWeek: function () { + return ( + '[el] dddd [pasado a la' + + (this.hours() !== 1 ? 's' : '') + + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: 'en %s', + past: 'hace %s', + s: 'unos segundos', + ss: '%d segundos', + m: 'un minuto', + mm: '%d minutos', + h: 'una hora', + hh: '%d horas', + d: 'un día', + dd: '%d días', + w: 'una semana', + ww: '%d semanas', + M: 'un mes', + MM: '%d meses', + y: 'un año', + yy: '%d años', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 0, // Sunday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + invalidDate: 'Fecha inválida', + }); + + return esMx; + +}))); + + +/***/ }), + +/***/ 56575: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Spanish (United States) [es-us] +//! author : bustta : https://github.com/bustta +//! author : chrisrodz : https://github.com/chrisrodz + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortDot = + 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split( + '_' + ), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'), + monthsParse = [ + /^ene/i, + /^feb/i, + /^mar/i, + /^abr/i, + /^may/i, + /^jun/i, + /^jul/i, + /^ago/i, + /^sep/i, + /^oct/i, + /^nov/i, + /^dic/i, + ], + monthsRegex = + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var esUs = moment.defineLocale('es-us', { + months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: + /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'MM/DD/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY h:mm A', + LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A', + }, + calendar: { + sameDay: function () { + return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextDay: function () { + return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextWeek: function () { + return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastDay: function () { + return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastWeek: function () { + return ( + '[el] dddd [pasado a la' + + (this.hours() !== 1 ? 's' : '') + + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: 'en %s', + past: 'hace %s', + s: 'unos segundos', + ss: '%d segundos', + m: 'un minuto', + mm: '%d minutos', + h: 'una hora', + hh: '%d horas', + d: 'un día', + dd: '%d días', + w: 'una semana', + ww: '%d semanas', + M: 'un mes', + MM: '%d meses', + y: 'un año', + yy: '%d años', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return esUs; + +}))); + + +/***/ }), + +/***/ 97650: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Spanish [es] +//! author : Julio Napurí : https://github.com/julionc + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortDot = + 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split( + '_' + ), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'), + monthsParse = [ + /^ene/i, + /^feb/i, + /^mar/i, + /^abr/i, + /^may/i, + /^jun/i, + /^jul/i, + /^ago/i, + /^sep/i, + /^oct/i, + /^nov/i, + /^dic/i, + ], + monthsRegex = + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var es = moment.defineLocale('es', { + months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: + /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY H:mm', + LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm', + }, + calendar: { + sameDay: function () { + return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextDay: function () { + return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + nextWeek: function () { + return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastDay: function () { + return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT'; + }, + lastWeek: function () { + return ( + '[el] dddd [pasado a la' + + (this.hours() !== 1 ? 's' : '') + + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: 'en %s', + past: 'hace %s', + s: 'unos segundos', + ss: '%d segundos', + m: 'un minuto', + mm: '%d minutos', + h: 'una hora', + hh: '%d horas', + d: 'un día', + dd: '%d días', + w: 'una semana', + ww: '%d semanas', + M: 'un mes', + MM: '%d meses', + y: 'un año', + yy: '%d años', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + invalidDate: 'Fecha inválida', + }); + + return es; + +}))); + + +/***/ }), + +/***/ 3035: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Estonian [et] +//! author : Henry Kehlmann : https://github.com/madhenry +//! improvements : Illimar Tambek : https://github.com/ragulka + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + s: ['mõne sekundi', 'mõni sekund', 'paar sekundit'], + ss: [number + 'sekundi', number + 'sekundit'], + m: ['ühe minuti', 'üks minut'], + mm: [number + ' minuti', number + ' minutit'], + h: ['ühe tunni', 'tund aega', 'üks tund'], + hh: [number + ' tunni', number + ' tundi'], + d: ['ühe päeva', 'üks päev'], + M: ['kuu aja', 'kuu aega', 'üks kuu'], + MM: [number + ' kuu', number + ' kuud'], + y: ['ühe aasta', 'aasta', 'üks aasta'], + yy: [number + ' aasta', number + ' aastat'], + }; + if (withoutSuffix) { + return format[key][2] ? format[key][2] : format[key][1]; + } + return isFuture ? format[key][0] : format[key][1]; + } + + var et = moment.defineLocale('et', { + months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split( + '_' + ), + monthsShort: + 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), + weekdays: + 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split( + '_' + ), + weekdaysShort: 'P_E_T_K_N_R_L'.split('_'), + weekdaysMin: 'P_E_T_K_N_R_L'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[Täna,] LT', + nextDay: '[Homme,] LT', + nextWeek: '[Järgmine] dddd LT', + lastDay: '[Eile,] LT', + lastWeek: '[Eelmine] dddd LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s pärast', + past: '%s tagasi', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: '%d päeva', + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return et; + +}))); + + +/***/ }), + +/***/ 3508: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Basque [eu] +//! author : Eneko Illarramendi : https://github.com/eillarra + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var eu = moment.defineLocale('eu', { + months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split( + '_' + ), + monthsShort: + 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split( + '_' + ), + weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'), + weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'YYYY[ko] MMMM[ren] D[a]', + LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm', + LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', + l: 'YYYY-M-D', + ll: 'YYYY[ko] MMM D[a]', + lll: 'YYYY[ko] MMM D[a] HH:mm', + llll: 'ddd, YYYY[ko] MMM D[a] HH:mm', + }, + calendar: { + sameDay: '[gaur] LT[etan]', + nextDay: '[bihar] LT[etan]', + nextWeek: 'dddd LT[etan]', + lastDay: '[atzo] LT[etan]', + lastWeek: '[aurreko] dddd LT[etan]', + sameElse: 'L', + }, + relativeTime: { + future: '%s barru', + past: 'duela %s', + s: 'segundo batzuk', + ss: '%d segundo', + m: 'minutu bat', + mm: '%d minutu', + h: 'ordu bat', + hh: '%d ordu', + d: 'egun bat', + dd: '%d egun', + M: 'hilabete bat', + MM: '%d hilabete', + y: 'urte bat', + yy: '%d urte', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return eu; + +}))); + + +/***/ }), + +/***/ 119: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Persian [fa] +//! author : Ebrahim Byagowi : https://github.com/ebraminio + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '۱', + 2: '۲', + 3: '۳', + 4: '۴', + 5: '۵', + 6: '۶', + 7: '۷', + 8: '۸', + 9: '۹', + 0: '۰', + }, + numberMap = { + '۱': '1', + '۲': '2', + '۳': '3', + '۴': '4', + '۵': '5', + '۶': '6', + '۷': '7', + '۸': '8', + '۹': '9', + '۰': '0', + }; + + var fa = moment.defineLocale('fa', { + months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split( + '_' + ), + monthsShort: + 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split( + '_' + ), + weekdays: + 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split( + '_' + ), + weekdaysShort: + 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split( + '_' + ), + weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + meridiemParse: /قبل از ظهر|بعد از ظهر/, + isPM: function (input) { + return /بعد از ظهر/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'قبل از ظهر'; + } else { + return 'بعد از ظهر'; + } + }, + calendar: { + sameDay: '[امروز ساعت] LT', + nextDay: '[فردا ساعت] LT', + nextWeek: 'dddd [ساعت] LT', + lastDay: '[دیروز ساعت] LT', + lastWeek: 'dddd [پیش] [ساعت] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'در %s', + past: '%s پیش', + s: 'چند ثانیه', + ss: '%d ثانیه', + m: 'یک دقیقه', + mm: '%d دقیقه', + h: 'یک ساعت', + hh: '%d ساعت', + d: 'یک روز', + dd: '%d روز', + M: 'یک ماه', + MM: '%d ماه', + y: 'یک سال', + yy: '%d سال', + }, + preparse: function (string) { + return string + .replace(/[۰-۹]/g, function (match) { + return numberMap[match]; + }) + .replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + dayOfMonthOrdinalParse: /\d{1,2}م/, + ordinal: '%dم', + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return fa; + +}))); + + +/***/ }), + +/***/ 90527: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Finnish [fi] +//! author : Tarmo Aidantausta : https://github.com/bleadof + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var numbersPast = + 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split( + ' ' + ), + numbersFuture = [ + 'nolla', + 'yhden', + 'kahden', + 'kolmen', + 'neljän', + 'viiden', + 'kuuden', + numbersPast[7], + numbersPast[8], + numbersPast[9], + ]; + function translate(number, withoutSuffix, key, isFuture) { + var result = ''; + switch (key) { + case 's': + return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; + case 'ss': + result = isFuture ? 'sekunnin' : 'sekuntia'; + break; + case 'm': + return isFuture ? 'minuutin' : 'minuutti'; + case 'mm': + result = isFuture ? 'minuutin' : 'minuuttia'; + break; + case 'h': + return isFuture ? 'tunnin' : 'tunti'; + case 'hh': + result = isFuture ? 'tunnin' : 'tuntia'; + break; + case 'd': + return isFuture ? 'päivän' : 'päivä'; + case 'dd': + result = isFuture ? 'päivän' : 'päivää'; + break; + case 'M': + return isFuture ? 'kuukauden' : 'kuukausi'; + case 'MM': + result = isFuture ? 'kuukauden' : 'kuukautta'; + break; + case 'y': + return isFuture ? 'vuoden' : 'vuosi'; + case 'yy': + result = isFuture ? 'vuoden' : 'vuotta'; + break; + } + result = verbalNumber(number, isFuture) + ' ' + result; + return result; + } + function verbalNumber(number, isFuture) { + return number < 10 + ? isFuture + ? numbersFuture[number] + : numbersPast[number] + : number; + } + + var fi = moment.defineLocale('fi', { + months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split( + '_' + ), + monthsShort: + 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split( + '_' + ), + weekdays: + 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split( + '_' + ), + weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'), + weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD.MM.YYYY', + LL: 'Do MMMM[ta] YYYY', + LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm', + LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', + l: 'D.M.YYYY', + ll: 'Do MMM YYYY', + lll: 'Do MMM YYYY, [klo] HH.mm', + llll: 'ddd, Do MMM YYYY, [klo] HH.mm', + }, + calendar: { + sameDay: '[tänään] [klo] LT', + nextDay: '[huomenna] [klo] LT', + nextWeek: 'dddd [klo] LT', + lastDay: '[eilen] [klo] LT', + lastWeek: '[viime] dddd[na] [klo] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s päästä', + past: '%s sitten', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return fi; + +}))); + + +/***/ }), + +/***/ 95995: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Filipino [fil] +//! author : Dan Hagman : https://github.com/hagmandan +//! author : Matthew Co : https://github.com/matthewdeeco + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var fil = moment.defineLocale('fil', { + months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split( + '_' + ), + monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), + weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split( + '_' + ), + weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), + weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'MM/D/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY HH:mm', + LLLL: 'dddd, MMMM DD, YYYY HH:mm', + }, + calendar: { + sameDay: 'LT [ngayong araw]', + nextDay: '[Bukas ng] LT', + nextWeek: 'LT [sa susunod na] dddd', + lastDay: 'LT [kahapon]', + lastWeek: 'LT [noong nakaraang] dddd', + sameElse: 'L', + }, + relativeTime: { + future: 'sa loob ng %s', + past: '%s ang nakalipas', + s: 'ilang segundo', + ss: '%d segundo', + m: 'isang minuto', + mm: '%d minuto', + h: 'isang oras', + hh: '%d oras', + d: 'isang araw', + dd: '%d araw', + M: 'isang buwan', + MM: '%d buwan', + y: 'isang taon', + yy: '%d taon', + }, + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal: function (number) { + return number; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return fil; + +}))); + + +/***/ }), + +/***/ 52477: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Faroese [fo] +//! author : Ragnar Johannesen : https://github.com/ragnar123 +//! author : Kristian Sakarisson : https://github.com/sakarisson + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var fo = moment.defineLocale('fo', { + months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split( + '_' + ), + monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), + weekdays: + 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split( + '_' + ), + weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'), + weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D. MMMM, YYYY HH:mm', + }, + calendar: { + sameDay: '[Í dag kl.] LT', + nextDay: '[Í morgin kl.] LT', + nextWeek: 'dddd [kl.] LT', + lastDay: '[Í gjár kl.] LT', + lastWeek: '[síðstu] dddd [kl] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'um %s', + past: '%s síðani', + s: 'fá sekund', + ss: '%d sekundir', + m: 'ein minuttur', + mm: '%d minuttir', + h: 'ein tími', + hh: '%d tímar', + d: 'ein dagur', + dd: '%d dagar', + M: 'ein mánaður', + MM: '%d mánaðir', + y: 'eitt ár', + yy: '%d ár', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return fo; + +}))); + + +/***/ }), + +/***/ 26435: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : French (Canada) [fr-ca] +//! author : Jonathan Abourbih : https://github.com/jonbca + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var frCa = moment.defineLocale('fr-ca', { + months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split( + '_' + ), + monthsShort: + 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Aujourd’hui à] LT', + nextDay: '[Demain à] LT', + nextWeek: 'dddd [à] LT', + lastDay: '[Hier à] LT', + lastWeek: 'dddd [dernier à] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dans %s', + past: 'il y a %s', + s: 'quelques secondes', + ss: '%d secondes', + m: 'une minute', + mm: '%d minutes', + h: 'une heure', + hh: '%d heures', + d: 'un jour', + dd: '%d jours', + M: 'un mois', + MM: '%d mois', + y: 'un an', + yy: '%d ans', + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, + ordinal: function (number, period) { + switch (period) { + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'D': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); + + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + }, + }); + + return frCa; + +}))); + + +/***/ }), + +/***/ 37892: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : French (Switzerland) [fr-ch] +//! author : Gaspard Bucher : https://github.com/gaspard + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var frCh = moment.defineLocale('fr-ch', { + months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split( + '_' + ), + monthsShort: + 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Aujourd’hui à] LT', + nextDay: '[Demain à] LT', + nextWeek: 'dddd [à] LT', + lastDay: '[Hier à] LT', + lastWeek: 'dddd [dernier à] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dans %s', + past: 'il y a %s', + s: 'quelques secondes', + ss: '%d secondes', + m: 'une minute', + mm: '%d minutes', + h: 'une heure', + hh: '%d heures', + d: 'un jour', + dd: '%d jours', + M: 'un mois', + MM: '%d mois', + y: 'un an', + yy: '%d ans', + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, + ordinal: function (number, period) { + switch (period) { + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'D': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); + + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return frCh; + +}))); + + +/***/ }), + +/***/ 85498: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : French [fr] +//! author : John Fischer : https://github.com/jfroffice + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsStrictRegex = + /^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i, + monthsShortStrictRegex = + /(janv\.?|févr\.?|mars|avr\.?|mai|juin|juil\.?|août|sept\.?|oct\.?|nov\.?|déc\.?)/i, + monthsRegex = + /(janv\.?|févr\.?|mars|avr\.?|mai|juin|juil\.?|août|sept\.?|oct\.?|nov\.?|déc\.?|janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i, + monthsParse = [ + /^janv/i, + /^févr/i, + /^mars/i, + /^avr/i, + /^mai/i, + /^juin/i, + /^juil/i, + /^août/i, + /^sept/i, + /^oct/i, + /^nov/i, + /^déc/i, + ]; + + var fr = moment.defineLocale('fr', { + months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split( + '_' + ), + monthsShort: + 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split( + '_' + ), + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: monthsStrictRegex, + monthsShortStrictRegex: monthsShortStrictRegex, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Aujourd’hui à] LT', + nextDay: '[Demain à] LT', + nextWeek: 'dddd [à] LT', + lastDay: '[Hier à] LT', + lastWeek: 'dddd [dernier à] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dans %s', + past: 'il y a %s', + s: 'quelques secondes', + ss: '%d secondes', + m: 'une minute', + mm: '%d minutes', + h: 'une heure', + hh: '%d heures', + d: 'un jour', + dd: '%d jours', + w: 'une semaine', + ww: '%d semaines', + M: 'un mois', + MM: '%d mois', + y: 'un an', + yy: '%d ans', + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|)/, + ordinal: function (number, period) { + switch (period) { + // TODO: Return 'e' when day of month > 1. Move this case inside + // block for masculine words below. + // See https://github.com/moment/moment/issues/3375 + case 'D': + return number + (number === 1 ? 'er' : ''); + + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); + + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return fr; + +}))); + + +/***/ }), + +/***/ 37071: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Frisian [fy] +//! author : Robin van der Vliet : https://github.com/robin0van0der0v + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortWithDots = + 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'), + monthsShortWithoutDots = + 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); + + var fy = moment.defineLocale('fy', { + months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, + monthsParseExact: true, + weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split( + '_' + ), + weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'), + weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD-MM-YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[hjoed om] LT', + nextDay: '[moarn om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[juster om] LT', + lastWeek: '[ôfrûne] dddd [om] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'oer %s', + past: '%s lyn', + s: 'in pear sekonden', + ss: '%d sekonden', + m: 'ien minút', + mm: '%d minuten', + h: 'ien oere', + hh: '%d oeren', + d: 'ien dei', + dd: '%d dagen', + M: 'ien moanne', + MM: '%d moannen', + y: 'ien jier', + yy: '%d jierren', + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal: function (number) { + return ( + number + + (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de') + ); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return fy; + +}))); + + +/***/ }), + +/***/ 41734: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Irish or Irish Gaelic [ga] +//! author : André Silva : https://github.com/askpt + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = [ + 'Eanáir', + 'Feabhra', + 'Márta', + 'Aibreán', + 'Bealtaine', + 'Meitheamh', + 'Iúil', + 'Lúnasa', + 'Meán Fómhair', + 'Deireadh Fómhair', + 'Samhain', + 'Nollaig', + ], + monthsShort = [ + 'Ean', + 'Feabh', + 'Márt', + 'Aib', + 'Beal', + 'Meith', + 'Iúil', + 'Lún', + 'M.F.', + 'D.F.', + 'Samh', + 'Noll', + ], + weekdays = [ + 'Dé Domhnaigh', + 'Dé Luain', + 'Dé Máirt', + 'Dé Céadaoin', + 'Déardaoin', + 'Dé hAoine', + 'Dé Sathairn', + ], + weekdaysShort = ['Domh', 'Luan', 'Máirt', 'Céad', 'Déar', 'Aoine', 'Sath'], + weekdaysMin = ['Do', 'Lu', 'Má', 'Cé', 'Dé', 'A', 'Sa']; + + var ga = moment.defineLocale('ga', { + months: months, + monthsShort: monthsShort, + monthsParseExact: true, + weekdays: weekdays, + weekdaysShort: weekdaysShort, + weekdaysMin: weekdaysMin, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Inniu ag] LT', + nextDay: '[Amárach ag] LT', + nextWeek: 'dddd [ag] LT', + lastDay: '[Inné ag] LT', + lastWeek: 'dddd [seo caite] [ag] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'i %s', + past: '%s ó shin', + s: 'cúpla soicind', + ss: '%d soicind', + m: 'nóiméad', + mm: '%d nóiméad', + h: 'uair an chloig', + hh: '%d uair an chloig', + d: 'lá', + dd: '%d lá', + M: 'mí', + MM: '%d míonna', + y: 'bliain', + yy: '%d bliain', + }, + dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/, + ordinal: function (number) { + var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return ga; + +}))); + + +/***/ }), + +/***/ 70217: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Scottish Gaelic [gd] +//! author : Jon Ashdown : https://github.com/jonashdown + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = [ + 'Am Faoilleach', + 'An Gearran', + 'Am Màrt', + 'An Giblean', + 'An Cèitean', + 'An t-Ògmhios', + 'An t-Iuchar', + 'An Lùnastal', + 'An t-Sultain', + 'An Dàmhair', + 'An t-Samhain', + 'An Dùbhlachd', + ], + monthsShort = [ + 'Faoi', + 'Gear', + 'Màrt', + 'Gibl', + 'Cèit', + 'Ògmh', + 'Iuch', + 'Lùn', + 'Sult', + 'Dàmh', + 'Samh', + 'Dùbh', + ], + weekdays = [ + 'Didòmhnaich', + 'Diluain', + 'Dimàirt', + 'Diciadain', + 'Diardaoin', + 'Dihaoine', + 'Disathairne', + ], + weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis'], + weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; + + var gd = moment.defineLocale('gd', { + months: months, + monthsShort: monthsShort, + monthsParseExact: true, + weekdays: weekdays, + weekdaysShort: weekdaysShort, + weekdaysMin: weekdaysMin, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[An-diugh aig] LT', + nextDay: '[A-màireach aig] LT', + nextWeek: 'dddd [aig] LT', + lastDay: '[An-dè aig] LT', + lastWeek: 'dddd [seo chaidh] [aig] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'ann an %s', + past: 'bho chionn %s', + s: 'beagan diogan', + ss: '%d diogan', + m: 'mionaid', + mm: '%d mionaidean', + h: 'uair', + hh: '%d uairean', + d: 'latha', + dd: '%d latha', + M: 'mìos', + MM: '%d mìosan', + y: 'bliadhna', + yy: '%d bliadhna', + }, + dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/, + ordinal: function (number) { + var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return gd; + +}))); + + +/***/ }), + +/***/ 77329: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Galician [gl] +//! author : Juan G. Hurtado : https://github.com/juanghurtado + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var gl = moment.defineLocale('gl', { + months: 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split( + '_' + ), + monthsShort: + 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), + weekdaysShort: 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), + weekdaysMin: 'do_lu_ma_mé_xo_ve_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY H:mm', + LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm', + }, + calendar: { + sameDay: function () { + return '[hoxe ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT'; + }, + nextDay: function () { + return '[mañá ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT'; + }, + nextWeek: function () { + return 'dddd [' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT'; + }, + lastDay: function () { + return '[onte ' + (this.hours() !== 1 ? 'á' : 'a') + '] LT'; + }, + lastWeek: function () { + return ( + '[o] dddd [pasado ' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT' + ); + }, + sameElse: 'L', + }, + relativeTime: { + future: function (str) { + if (str.indexOf('un') === 0) { + return 'n' + str; + } + return 'en ' + str; + }, + past: 'hai %s', + s: 'uns segundos', + ss: '%d segundos', + m: 'un minuto', + mm: '%d minutos', + h: 'unha hora', + hh: '%d horas', + d: 'un día', + dd: '%d días', + M: 'un mes', + MM: '%d meses', + y: 'un ano', + yy: '%d anos', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return gl; + +}))); + + +/***/ }), + +/***/ 32124: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Konkani Devanagari script [gom-deva] +//! author : The Discoverer : https://github.com/WikiDiscoverer + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + s: ['थोडया सॅकंडांनी', 'थोडे सॅकंड'], + ss: [number + ' सॅकंडांनी', number + ' सॅकंड'], + m: ['एका मिणटान', 'एक मिनूट'], + mm: [number + ' मिणटांनी', number + ' मिणटां'], + h: ['एका वरान', 'एक वर'], + hh: [number + ' वरांनी', number + ' वरां'], + d: ['एका दिसान', 'एक दीस'], + dd: [number + ' दिसांनी', number + ' दीस'], + M: ['एका म्हयन्यान', 'एक म्हयनो'], + MM: [number + ' म्हयन्यानी', number + ' म्हयने'], + y: ['एका वर्सान', 'एक वर्स'], + yy: [number + ' वर्सांनी', number + ' वर्सां'], + }; + return isFuture ? format[key][0] : format[key][1]; + } + + var gomDeva = moment.defineLocale('gom-deva', { + months: { + standalone: + 'जानेवारी_फेब्रुवारी_मार्च_एप्रील_मे_जून_जुलय_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split( + '_' + ), + format: 'जानेवारीच्या_फेब्रुवारीच्या_मार्चाच्या_एप्रीलाच्या_मेयाच्या_जूनाच्या_जुलयाच्या_ऑगस्टाच्या_सप्टेंबराच्या_ऑक्टोबराच्या_नोव्हेंबराच्या_डिसेंबराच्या'.split( + '_' + ), + isFormat: /MMMM(\s)+D[oD]?/, + }, + monthsShort: + 'जाने._फेब्रु._मार्च_एप्री._मे_जून_जुल._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'आयतार_सोमार_मंगळार_बुधवार_बिरेस्तार_सुक्रार_शेनवार'.split('_'), + weekdaysShort: 'आयत._सोम._मंगळ._बुध._ब्रेस्त._सुक्र._शेन.'.split('_'), + weekdaysMin: 'आ_सो_मं_बु_ब्रे_सु_शे'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'A h:mm [वाजतां]', + LTS: 'A h:mm:ss [वाजतां]', + L: 'DD-MM-YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY A h:mm [वाजतां]', + LLLL: 'dddd, MMMM Do, YYYY, A h:mm [वाजतां]', + llll: 'ddd, D MMM YYYY, A h:mm [वाजतां]', + }, + calendar: { + sameDay: '[आयज] LT', + nextDay: '[फाल्यां] LT', + nextWeek: '[फुडलो] dddd[,] LT', + lastDay: '[काल] LT', + lastWeek: '[फाटलो] dddd[,] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s', + past: '%s आदीं', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: processRelativeTime, + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}(वेर)/, + ordinal: function (number, period) { + switch (period) { + // the ordinal 'वेर' only applies to day of the month + case 'D': + return number + 'वेर'; + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + case 'w': + case 'W': + return number; + } + }, + week: { + dow: 0, // Sunday is the first day of the week + doy: 3, // The week that contains Jan 4th is the first week of the year (7 + 0 - 4) + }, + meridiemParse: /राती|सकाळीं|दनपारां|सांजे/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'राती') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'सकाळीं') { + return hour; + } else if (meridiem === 'दनपारां') { + return hour > 12 ? hour : hour + 12; + } else if (meridiem === 'सांजे') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'राती'; + } else if (hour < 12) { + return 'सकाळीं'; + } else if (hour < 16) { + return 'दनपारां'; + } else if (hour < 20) { + return 'सांजे'; + } else { + return 'राती'; + } + }, + }); + + return gomDeva; + +}))); + + +/***/ }), + +/***/ 93383: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Konkani Latin script [gom-latn] +//! author : The Discoverer : https://github.com/WikiDiscoverer + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + s: ['thoddea sekondamni', 'thodde sekond'], + ss: [number + ' sekondamni', number + ' sekond'], + m: ['eka mintan', 'ek minut'], + mm: [number + ' mintamni', number + ' mintam'], + h: ['eka voran', 'ek vor'], + hh: [number + ' voramni', number + ' voram'], + d: ['eka disan', 'ek dis'], + dd: [number + ' disamni', number + ' dis'], + M: ['eka mhoinean', 'ek mhoino'], + MM: [number + ' mhoineamni', number + ' mhoine'], + y: ['eka vorsan', 'ek voros'], + yy: [number + ' vorsamni', number + ' vorsam'], + }; + return isFuture ? format[key][0] : format[key][1]; + } + + var gomLatn = moment.defineLocale('gom-latn', { + months: { + standalone: + 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split( + '_' + ), + format: 'Janerachea_Febrerachea_Marsachea_Abrilachea_Maiachea_Junachea_Julaiachea_Agostachea_Setembrachea_Otubrachea_Novembrachea_Dezembrachea'.split( + '_' + ), + isFormat: /MMMM(\s)+D[oD]?/, + }, + monthsShort: + 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'), + monthsParseExact: true, + weekdays: "Aitar_Somar_Mongllar_Budhvar_Birestar_Sukrar_Son'var".split('_'), + weekdaysShort: 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'), + weekdaysMin: 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'A h:mm [vazta]', + LTS: 'A h:mm:ss [vazta]', + L: 'DD-MM-YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY A h:mm [vazta]', + LLLL: 'dddd, MMMM Do, YYYY, A h:mm [vazta]', + llll: 'ddd, D MMM YYYY, A h:mm [vazta]', + }, + calendar: { + sameDay: '[Aiz] LT', + nextDay: '[Faleam] LT', + nextWeek: '[Fuddlo] dddd[,] LT', + lastDay: '[Kal] LT', + lastWeek: '[Fattlo] dddd[,] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s', + past: '%s adim', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: processRelativeTime, + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}(er)/, + ordinal: function (number, period) { + switch (period) { + // the ordinal 'er' only applies to day of the month + case 'D': + return number + 'er'; + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + case 'w': + case 'W': + return number; + } + }, + week: { + dow: 0, // Sunday is the first day of the week + doy: 3, // The week that contains Jan 4th is the first week of the year (7 + 0 - 4) + }, + meridiemParse: /rati|sokallim|donparam|sanje/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'rati') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'sokallim') { + return hour; + } else if (meridiem === 'donparam') { + return hour > 12 ? hour : hour + 12; + } else if (meridiem === 'sanje') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'rati'; + } else if (hour < 12) { + return 'sokallim'; + } else if (hour < 16) { + return 'donparam'; + } else if (hour < 20) { + return 'sanje'; + } else { + return 'rati'; + } + }, + }); + + return gomLatn; + +}))); + + +/***/ }), + +/***/ 95050: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Gujarati [gu] +//! author : Kaushik Thanki : https://github.com/Kaushik1987 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '૧', + 2: '૨', + 3: '૩', + 4: '૪', + 5: '૫', + 6: '૬', + 7: '૭', + 8: '૮', + 9: '૯', + 0: '૦', + }, + numberMap = { + '૧': '1', + '૨': '2', + '૩': '3', + '૪': '4', + '૫': '5', + '૬': '6', + '૭': '7', + '૮': '8', + '૯': '9', + '૦': '0', + }; + + var gu = moment.defineLocale('gu', { + months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split( + '_' + ), + monthsShort: + 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split( + '_' + ), + weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'), + weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'), + longDateFormat: { + LT: 'A h:mm વાગ્યે', + LTS: 'A h:mm:ss વાગ્યે', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm વાગ્યે', + LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે', + }, + calendar: { + sameDay: '[આજ] LT', + nextDay: '[કાલે] LT', + nextWeek: 'dddd, LT', + lastDay: '[ગઇકાલે] LT', + lastWeek: '[પાછલા] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s મા', + past: '%s પહેલા', + s: 'અમુક પળો', + ss: '%d સેકંડ', + m: 'એક મિનિટ', + mm: '%d મિનિટ', + h: 'એક કલાક', + hh: '%d કલાક', + d: 'એક દિવસ', + dd: '%d દિવસ', + M: 'એક મહિનો', + MM: '%d મહિનો', + y: 'એક વર્ષ', + yy: '%d વર્ષ', + }, + preparse: function (string) { + return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Gujarati notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati. + meridiemParse: /રાત|બપોર|સવાર|સાંજ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'રાત') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'સવાર') { + return hour; + } else if (meridiem === 'બપોર') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'સાંજ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'રાત'; + } else if (hour < 10) { + return 'સવાર'; + } else if (hour < 17) { + return 'બપોર'; + } else if (hour < 20) { + return 'સાંજ'; + } else { + return 'રાત'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return gu; + +}))); + + +/***/ }), + +/***/ 11713: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Hebrew [he] +//! author : Tomer Cohen : https://github.com/tomer +//! author : Moshe Simantov : https://github.com/DevelopmentIL +//! author : Tal Ater : https://github.com/TalAter + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var he = moment.defineLocale('he', { + months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split( + '_' + ), + monthsShort: + 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), + weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), + weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), + weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [ב]MMMM YYYY', + LLL: 'D [ב]MMMM YYYY HH:mm', + LLLL: 'dddd, D [ב]MMMM YYYY HH:mm', + l: 'D/M/YYYY', + ll: 'D MMM YYYY', + lll: 'D MMM YYYY HH:mm', + llll: 'ddd, D MMM YYYY HH:mm', + }, + calendar: { + sameDay: '[היום ב־]LT', + nextDay: '[מחר ב־]LT', + nextWeek: 'dddd [בשעה] LT', + lastDay: '[אתמול ב־]LT', + lastWeek: '[ביום] dddd [האחרון בשעה] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'בעוד %s', + past: 'לפני %s', + s: 'מספר שניות', + ss: '%d שניות', + m: 'דקה', + mm: '%d דקות', + h: 'שעה', + hh: function (number) { + if (number === 2) { + return 'שעתיים'; + } + return number + ' שעות'; + }, + d: 'יום', + dd: function (number) { + if (number === 2) { + return 'יומיים'; + } + return number + ' ימים'; + }, + M: 'חודש', + MM: function (number) { + if (number === 2) { + return 'חודשיים'; + } + return number + ' חודשים'; + }, + y: 'שנה', + yy: function (number) { + if (number === 2) { + return 'שנתיים'; + } else if (number % 10 === 0 && number !== 10) { + return number + ' שנה'; + } + return number + ' שנים'; + }, + }, + meridiemParse: + /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, + isPM: function (input) { + return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 5) { + return 'לפנות בוקר'; + } else if (hour < 10) { + return 'בבוקר'; + } else if (hour < 12) { + return isLower ? 'לפנה"צ' : 'לפני הצהריים'; + } else if (hour < 18) { + return isLower ? 'אחה"צ' : 'אחרי הצהריים'; + } else { + return 'בערב'; + } + }, + }); + + return he; + +}))); + + +/***/ }), + +/***/ 43861: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Hindi [hi] +//! author : Mayank Singhal : https://github.com/mayanksinghal + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '१', + 2: '२', + 3: '३', + 4: '४', + 5: '५', + 6: '६', + 7: '७', + 8: '८', + 9: '९', + 0: '०', + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0', + }, + monthsParse = [ + /^जन/i, + /^फ़र|फर/i, + /^मार्च/i, + /^अप्रै/i, + /^मई/i, + /^जून/i, + /^जुल/i, + /^अग/i, + /^सितं|सित/i, + /^अक्टू/i, + /^नव|नवं/i, + /^दिसं|दिस/i, + ], + shortMonthsParse = [ + /^जन/i, + /^फ़र/i, + /^मार्च/i, + /^अप्रै/i, + /^मई/i, + /^जून/i, + /^जुल/i, + /^अग/i, + /^सित/i, + /^अक्टू/i, + /^नव/i, + /^दिस/i, + ]; + + var hi = moment.defineLocale('hi', { + months: { + format: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split( + '_' + ), + standalone: + 'जनवरी_फरवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितंबर_अक्टूबर_नवंबर_दिसंबर'.split( + '_' + ), + }, + monthsShort: + 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), + weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), + weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), + weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), + longDateFormat: { + LT: 'A h:mm बजे', + LTS: 'A h:mm:ss बजे', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm बजे', + LLLL: 'dddd, D MMMM YYYY, A h:mm बजे', + }, + + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: shortMonthsParse, + + monthsRegex: + /^(जनवरी|जन\.?|फ़रवरी|फरवरी|फ़र\.?|मार्च?|अप्रैल|अप्रै\.?|मई?|जून?|जुलाई|जुल\.?|अगस्त|अग\.?|सितम्बर|सितंबर|सित\.?|अक्टूबर|अक्टू\.?|नवम्बर|नवंबर|नव\.?|दिसम्बर|दिसंबर|दिस\.?)/i, + + monthsShortRegex: + /^(जनवरी|जन\.?|फ़रवरी|फरवरी|फ़र\.?|मार्च?|अप्रैल|अप्रै\.?|मई?|जून?|जुलाई|जुल\.?|अगस्त|अग\.?|सितम्बर|सितंबर|सित\.?|अक्टूबर|अक्टू\.?|नवम्बर|नवंबर|नव\.?|दिसम्बर|दिसंबर|दिस\.?)/i, + + monthsStrictRegex: + /^(जनवरी?|फ़रवरी|फरवरी?|मार्च?|अप्रैल?|मई?|जून?|जुलाई?|अगस्त?|सितम्बर|सितंबर|सित?\.?|अक्टूबर|अक्टू\.?|नवम्बर|नवंबर?|दिसम्बर|दिसंबर?)/i, + + monthsShortStrictRegex: + /^(जन\.?|फ़र\.?|मार्च?|अप्रै\.?|मई?|जून?|जुल\.?|अग\.?|सित\.?|अक्टू\.?|नव\.?|दिस\.?)/i, + + calendar: { + sameDay: '[आज] LT', + nextDay: '[कल] LT', + nextWeek: 'dddd, LT', + lastDay: '[कल] LT', + lastWeek: '[पिछले] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s में', + past: '%s पहले', + s: 'कुछ ही क्षण', + ss: '%d सेकंड', + m: 'एक मिनट', + mm: '%d मिनट', + h: 'एक घंटा', + hh: '%d घंटे', + d: 'एक दिन', + dd: '%d दिन', + M: 'एक महीने', + MM: '%d महीने', + y: 'एक वर्ष', + yy: '%d वर्ष', + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Hindi notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. + meridiemParse: /रात|सुबह|दोपहर|शाम/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'रात') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'सुबह') { + return hour; + } else if (meridiem === 'दोपहर') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'शाम') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'रात'; + } else if (hour < 10) { + return 'सुबह'; + } else if (hour < 17) { + return 'दोपहर'; + } else if (hour < 20) { + return 'शाम'; + } else { + return 'रात'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return hi; + +}))); + + +/***/ }), + +/***/ 26308: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Croatian [hr] +//! author : Bojan Marković : https://github.com/bmarkovic + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + if (number === 1) { + result += 'sekunda'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sekunde'; + } else { + result += 'sekundi'; + } + return result; + case 'm': + return withoutSuffix ? 'jedna minuta' : 'jedne minute'; + case 'mm': + if (number === 1) { + result += 'minuta'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'minute'; + } else { + result += 'minuta'; + } + return result; + case 'h': + return withoutSuffix ? 'jedan sat' : 'jednog sata'; + case 'hh': + if (number === 1) { + result += 'sat'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sata'; + } else { + result += 'sati'; + } + return result; + case 'dd': + if (number === 1) { + result += 'dan'; + } else { + result += 'dana'; + } + return result; + case 'MM': + if (number === 1) { + result += 'mjesec'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'mjeseca'; + } else { + result += 'mjeseci'; + } + return result; + case 'yy': + if (number === 1) { + result += 'godina'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'godine'; + } else { + result += 'godina'; + } + return result; + } + } + + var hr = moment.defineLocale('hr', { + months: { + format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split( + '_' + ), + standalone: + 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split( + '_' + ), + }, + monthsShort: + 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split( + '_' + ), + weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'Do MMMM YYYY', + LLL: 'Do MMMM YYYY H:mm', + LLLL: 'dddd, Do MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[danas u] LT', + nextDay: '[sutra u] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay: '[jučer u] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[prošlu] [nedjelju] [u] LT'; + case 3: + return '[prošlu] [srijedu] [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prošli] dddd [u] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'prije %s', + s: 'par sekundi', + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: 'dan', + dd: translate, + M: 'mjesec', + MM: translate, + y: 'godinu', + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return hr; + +}))); + + +/***/ }), + +/***/ 90609: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Hungarian [hu] +//! author : Adam Brunner : https://github.com/adambrunner +//! author : Peter Viszt : https://github.com/passatgt + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var weekEndings = + 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); + function translate(number, withoutSuffix, key, isFuture) { + var num = number; + switch (key) { + case 's': + return isFuture || withoutSuffix + ? 'néhány másodperc' + : 'néhány másodperce'; + case 'ss': + return num + (isFuture || withoutSuffix) + ? ' másodperc' + : ' másodperce'; + case 'm': + return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); + case 'mm': + return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); + case 'h': + return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); + case 'hh': + return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); + case 'd': + return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); + case 'dd': + return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); + case 'M': + return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); + case 'MM': + return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); + case 'y': + return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); + case 'yy': + return num + (isFuture || withoutSuffix ? ' év' : ' éve'); + } + return ''; + } + function week(isFuture) { + return ( + (isFuture ? '' : '[múlt] ') + + '[' + + weekEndings[this.day()] + + '] LT[-kor]' + ); + } + + var hu = moment.defineLocale('hu', { + months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split( + '_' + ), + monthsShort: + 'jan._feb._márc._ápr._máj._jún._júl._aug._szept._okt._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), + weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), + weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'YYYY.MM.DD.', + LL: 'YYYY. MMMM D.', + LLL: 'YYYY. MMMM D. H:mm', + LLLL: 'YYYY. MMMM D., dddd H:mm', + }, + meridiemParse: /de|du/i, + isPM: function (input) { + return input.charAt(1).toLowerCase() === 'u'; + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 12) { + return isLower === true ? 'de' : 'DE'; + } else { + return isLower === true ? 'du' : 'DU'; + } + }, + calendar: { + sameDay: '[ma] LT[-kor]', + nextDay: '[holnap] LT[-kor]', + nextWeek: function () { + return week.call(this, true); + }, + lastDay: '[tegnap] LT[-kor]', + lastWeek: function () { + return week.call(this, false); + }, + sameElse: 'L', + }, + relativeTime: { + future: '%s múlva', + past: '%s', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return hu; + +}))); + + +/***/ }), + +/***/ 17160: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Armenian [hy-am] +//! author : Armendarabyan : https://github.com/armendarabyan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var hyAm = moment.defineLocale('hy-am', { + months: { + format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split( + '_' + ), + standalone: + 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split( + '_' + ), + }, + monthsShort: 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), + weekdays: + 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split( + '_' + ), + weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), + weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY թ.', + LLL: 'D MMMM YYYY թ., HH:mm', + LLLL: 'dddd, D MMMM YYYY թ., HH:mm', + }, + calendar: { + sameDay: '[այսօր] LT', + nextDay: '[վաղը] LT', + lastDay: '[երեկ] LT', + nextWeek: function () { + return 'dddd [օրը ժամը] LT'; + }, + lastWeek: function () { + return '[անցած] dddd [օրը ժամը] LT'; + }, + sameElse: 'L', + }, + relativeTime: { + future: '%s հետո', + past: '%s առաջ', + s: 'մի քանի վայրկյան', + ss: '%d վայրկյան', + m: 'րոպե', + mm: '%d րոպե', + h: 'ժամ', + hh: '%d ժամ', + d: 'օր', + dd: '%d օր', + M: 'ամիս', + MM: '%d ամիս', + y: 'տարի', + yy: '%d տարի', + }, + meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, + isPM: function (input) { + return /^(ցերեկվա|երեկոյան)$/.test(input); + }, + meridiem: function (hour) { + if (hour < 4) { + return 'գիշերվա'; + } else if (hour < 12) { + return 'առավոտվա'; + } else if (hour < 17) { + return 'ցերեկվա'; + } else { + return 'երեկոյան'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, + ordinal: function (number, period) { + switch (period) { + case 'DDD': + case 'w': + case 'W': + case 'DDDo': + if (number === 1) { + return number + '-ին'; + } + return number + '-րդ'; + default: + return number; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return hyAm; + +}))); + + +/***/ }), + +/***/ 74063: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Indonesian [id] +//! author : Mohammad Satrio Utomo : https://github.com/tyok +//! reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var id = moment.defineLocale('id', { + months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'), + weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), + weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), + weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [pukul] HH.mm', + LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', + }, + meridiemParse: /pagi|siang|sore|malam/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'siang') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'sore' || meridiem === 'malam') { + return hour + 12; + } + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'siang'; + } else if (hours < 19) { + return 'sore'; + } else { + return 'malam'; + } + }, + calendar: { + sameDay: '[Hari ini pukul] LT', + nextDay: '[Besok pukul] LT', + nextWeek: 'dddd [pukul] LT', + lastDay: '[Kemarin pukul] LT', + lastWeek: 'dddd [lalu pukul] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dalam %s', + past: '%s yang lalu', + s: 'beberapa detik', + ss: '%d detik', + m: 'semenit', + mm: '%d menit', + h: 'sejam', + hh: '%d jam', + d: 'sehari', + dd: '%d hari', + M: 'sebulan', + MM: '%d bulan', + y: 'setahun', + yy: '%d tahun', + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return id; + +}))); + + +/***/ }), + +/***/ 89374: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Icelandic [is] +//! author : Hinrik Örn Sigurðsson : https://github.com/hinrik + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function plural(n) { + if (n % 100 === 11) { + return true; + } else if (n % 10 === 1) { + return false; + } + return true; + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': + return withoutSuffix || isFuture + ? 'nokkrar sekúndur' + : 'nokkrum sekúndum'; + case 'ss': + if (plural(number)) { + return ( + result + + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum') + ); + } + return result + 'sekúnda'; + case 'm': + return withoutSuffix ? 'mínúta' : 'mínútu'; + case 'mm': + if (plural(number)) { + return ( + result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum') + ); + } else if (withoutSuffix) { + return result + 'mínúta'; + } + return result + 'mínútu'; + case 'hh': + if (plural(number)) { + return ( + result + + (withoutSuffix || isFuture + ? 'klukkustundir' + : 'klukkustundum') + ); + } + return result + 'klukkustund'; + case 'd': + if (withoutSuffix) { + return 'dagur'; + } + return isFuture ? 'dag' : 'degi'; + case 'dd': + if (plural(number)) { + if (withoutSuffix) { + return result + 'dagar'; + } + return result + (isFuture ? 'daga' : 'dögum'); + } else if (withoutSuffix) { + return result + 'dagur'; + } + return result + (isFuture ? 'dag' : 'degi'); + case 'M': + if (withoutSuffix) { + return 'mánuður'; + } + return isFuture ? 'mánuð' : 'mánuði'; + case 'MM': + if (plural(number)) { + if (withoutSuffix) { + return result + 'mánuðir'; + } + return result + (isFuture ? 'mánuði' : 'mánuðum'); + } else if (withoutSuffix) { + return result + 'mánuður'; + } + return result + (isFuture ? 'mánuð' : 'mánuði'); + case 'y': + return withoutSuffix || isFuture ? 'ár' : 'ári'; + case 'yy': + if (plural(number)) { + return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); + } + return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); + } + } + + var is = moment.defineLocale('is', { + months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split( + '_' + ), + monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), + weekdays: + 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split( + '_' + ), + weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'), + weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY [kl.] H:mm', + LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm', + }, + calendar: { + sameDay: '[í dag kl.] LT', + nextDay: '[á morgun kl.] LT', + nextWeek: 'dddd [kl.] LT', + lastDay: '[í gær kl.] LT', + lastWeek: '[síðasta] dddd [kl.] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'eftir %s', + past: 'fyrir %s síðan', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: 'klukkustund', + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return is; + +}))); + + +/***/ }), + +/***/ 21827: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Italian (Switzerland) [it-ch] +//! author : xfh : https://github.com/xfh + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var itCh = moment.defineLocale('it-ch', { + months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split( + '_' + ), + monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), + weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split( + '_' + ), + weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'), + weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Oggi alle] LT', + nextDay: '[Domani alle] LT', + nextWeek: 'dddd [alle] LT', + lastDay: '[Ieri alle] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[la scorsa] dddd [alle] LT'; + default: + return '[lo scorso] dddd [alle] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: function (s) { + return (/^[0-9].+$/.test(s) ? 'tra' : 'in') + ' ' + s; + }, + past: '%s fa', + s: 'alcuni secondi', + ss: '%d secondi', + m: 'un minuto', + mm: '%d minuti', + h: "un'ora", + hh: '%d ore', + d: 'un giorno', + dd: '%d giorni', + M: 'un mese', + MM: '%d mesi', + y: 'un anno', + yy: '%d anni', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return itCh; + +}))); + + +/***/ }), + +/***/ 88383: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Italian [it] +//! author : Lorenzo : https://github.com/aliem +//! author: Mattia Larentis: https://github.com/nostalgiaz +//! author: Marco : https://github.com/Manfre98 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var it = moment.defineLocale('it', { + months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split( + '_' + ), + monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), + weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split( + '_' + ), + weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'), + weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: function () { + return ( + '[Oggi a' + + (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : "ll'") + + ']LT' + ); + }, + nextDay: function () { + return ( + '[Domani a' + + (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : "ll'") + + ']LT' + ); + }, + nextWeek: function () { + return ( + 'dddd [a' + + (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : "ll'") + + ']LT' + ); + }, + lastDay: function () { + return ( + '[Ieri a' + + (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : "ll'") + + ']LT' + ); + }, + lastWeek: function () { + switch (this.day()) { + case 0: + return ( + '[La scorsa] dddd [a' + + (this.hours() > 1 + ? 'lle ' + : this.hours() === 0 + ? ' ' + : "ll'") + + ']LT' + ); + default: + return ( + '[Lo scorso] dddd [a' + + (this.hours() > 1 + ? 'lle ' + : this.hours() === 0 + ? ' ' + : "ll'") + + ']LT' + ); + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'tra %s', + past: '%s fa', + s: 'alcuni secondi', + ss: '%d secondi', + m: 'un minuto', + mm: '%d minuti', + h: "un'ora", + hh: '%d ore', + d: 'un giorno', + dd: '%d giorni', + w: 'una settimana', + ww: '%d settimane', + M: 'un mese', + MM: '%d mesi', + y: 'un anno', + yy: '%d anni', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return it; + +}))); + + +/***/ }), + +/***/ 23827: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Japanese [ja] +//! author : LI Long : https://github.com/baryon + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ja = moment.defineLocale('ja', { + eras: [ + { + since: '2019-05-01', + offset: 1, + name: '令和', + narrow: '㋿', + abbr: 'R', + }, + { + since: '1989-01-08', + until: '2019-04-30', + offset: 1, + name: '平成', + narrow: '㍻', + abbr: 'H', + }, + { + since: '1926-12-25', + until: '1989-01-07', + offset: 1, + name: '昭和', + narrow: '㍼', + abbr: 'S', + }, + { + since: '1912-07-30', + until: '1926-12-24', + offset: 1, + name: '大正', + narrow: '㍽', + abbr: 'T', + }, + { + since: '1873-01-01', + until: '1912-07-29', + offset: 6, + name: '明治', + narrow: '㍾', + abbr: 'M', + }, + { + since: '0001-01-01', + until: '1873-12-31', + offset: 1, + name: '西暦', + narrow: 'AD', + abbr: 'AD', + }, + { + since: '0000-12-31', + until: -Infinity, + offset: 1, + name: '紀元前', + narrow: 'BC', + abbr: 'BC', + }, + ], + eraYearOrdinalRegex: /(元|\d+)年/, + eraYearOrdinalParse: function (input, match) { + return match[1] === '元' ? 1 : parseInt(match[1] || input, 10); + }, + months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split( + '_' + ), + weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), + weekdaysShort: '日_月_火_水_木_金_土'.split('_'), + weekdaysMin: '日_月_火_水_木_金_土'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日 HH:mm', + LLLL: 'YYYY年M月D日 dddd HH:mm', + l: 'YYYY/MM/DD', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日(ddd) HH:mm', + }, + meridiemParse: /午前|午後/i, + isPM: function (input) { + return input === '午後'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return '午前'; + } else { + return '午後'; + } + }, + calendar: { + sameDay: '[今日] LT', + nextDay: '[明日] LT', + nextWeek: function (now) { + if (now.week() !== this.week()) { + return '[来週]dddd LT'; + } else { + return 'dddd LT'; + } + }, + lastDay: '[昨日] LT', + lastWeek: function (now) { + if (this.week() !== now.week()) { + return '[先週]dddd LT'; + } else { + return 'dddd LT'; + } + }, + sameElse: 'L', + }, + dayOfMonthOrdinalParse: /\d{1,2}日/, + ordinal: function (number, period) { + switch (period) { + case 'y': + return number === 1 ? '元年' : number + '年'; + case 'd': + case 'D': + case 'DDD': + return number + '日'; + default: + return number; + } + }, + relativeTime: { + future: '%s後', + past: '%s前', + s: '数秒', + ss: '%d秒', + m: '1分', + mm: '%d分', + h: '1時間', + hh: '%d時間', + d: '1日', + dd: '%d日', + M: '1ヶ月', + MM: '%dヶ月', + y: '1年', + yy: '%d年', + }, + }); + + return ja; + +}))); + + +/***/ }), + +/***/ 89722: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Javanese [jv] +//! author : Rony Lantip : https://github.com/lantip +//! reference: http://jv.wikipedia.org/wiki/Basa_Jawa + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var jv = moment.defineLocale('jv', { + months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), + weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), + weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), + weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [pukul] HH.mm', + LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', + }, + meridiemParse: /enjing|siyang|sonten|ndalu/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'enjing') { + return hour; + } else if (meridiem === 'siyang') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'sonten' || meridiem === 'ndalu') { + return hour + 12; + } + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 11) { + return 'enjing'; + } else if (hours < 15) { + return 'siyang'; + } else if (hours < 19) { + return 'sonten'; + } else { + return 'ndalu'; + } + }, + calendar: { + sameDay: '[Dinten puniko pukul] LT', + nextDay: '[Mbenjang pukul] LT', + nextWeek: 'dddd [pukul] LT', + lastDay: '[Kala wingi pukul] LT', + lastWeek: 'dddd [kepengker pukul] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'wonten ing %s', + past: '%s ingkang kepengker', + s: 'sawetawis detik', + ss: '%d detik', + m: 'setunggal menit', + mm: '%d menit', + h: 'setunggal jam', + hh: '%d jam', + d: 'sedinten', + dd: '%d dinten', + M: 'sewulan', + MM: '%d wulan', + y: 'setaun', + yy: '%d taun', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return jv; + +}))); + + +/***/ }), + +/***/ 41794: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Georgian [ka] +//! author : Irakli Janiashvili : https://github.com/IrakliJani + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ka = moment.defineLocale('ka', { + months: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split( + '_' + ), + monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), + weekdays: { + standalone: + 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split( + '_' + ), + format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split( + '_' + ), + isFormat: /(წინა|შემდეგ)/, + }, + weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), + weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[დღეს] LT[-ზე]', + nextDay: '[ხვალ] LT[-ზე]', + lastDay: '[გუშინ] LT[-ზე]', + nextWeek: '[შემდეგ] dddd LT[-ზე]', + lastWeek: '[წინა] dddd LT-ზე', + sameElse: 'L', + }, + relativeTime: { + future: function (s) { + return s.replace( + /(წამ|წუთ|საათ|წელ|დღ|თვ)(ი|ე)/, + function ($0, $1, $2) { + return $2 === 'ი' ? $1 + 'ში' : $1 + $2 + 'ში'; + } + ); + }, + past: function (s) { + if (/(წამი|წუთი|საათი|დღე|თვე)/.test(s)) { + return s.replace(/(ი|ე)$/, 'ის წინ'); + } + if (/წელი/.test(s)) { + return s.replace(/წელი$/, 'წლის წინ'); + } + return s; + }, + s: 'რამდენიმე წამი', + ss: '%d წამი', + m: 'წუთი', + mm: '%d წუთი', + h: 'საათი', + hh: '%d საათი', + d: 'დღე', + dd: '%d დღე', + M: 'თვე', + MM: '%d თვე', + y: 'წელი', + yy: '%d წელი', + }, + dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, + ordinal: function (number) { + if (number === 0) { + return number; + } + if (number === 1) { + return number + '-ლი'; + } + if ( + number < 20 || + (number <= 100 && number % 20 === 0) || + number % 100 === 0 + ) { + return 'მე-' + number; + } + return number + '-ე'; + }, + week: { + dow: 1, + doy: 7, + }, + }); + + return ka; + +}))); + + +/***/ }), + +/***/ 27088: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Kazakh [kk] +//! authors : Nurlan Rakhimzhanov : https://github.com/nurlan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 0: '-ші', + 1: '-ші', + 2: '-ші', + 3: '-ші', + 4: '-ші', + 5: '-ші', + 6: '-шы', + 7: '-ші', + 8: '-ші', + 9: '-шы', + 10: '-шы', + 20: '-шы', + 30: '-шы', + 40: '-шы', + 50: '-ші', + 60: '-шы', + 70: '-ші', + 80: '-ші', + 90: '-шы', + 100: '-ші', + }; + + var kk = moment.defineLocale('kk', { + months: 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split( + '_' + ), + monthsShort: 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), + weekdays: 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split( + '_' + ), + weekdaysShort: 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), + weekdaysMin: 'жк_дй_сй_ср_бй_жм_сн'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Бүгін сағат] LT', + nextDay: '[Ертең сағат] LT', + nextWeek: 'dddd [сағат] LT', + lastDay: '[Кеше сағат] LT', + lastWeek: '[Өткен аптаның] dddd [сағат] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s ішінде', + past: '%s бұрын', + s: 'бірнеше секунд', + ss: '%d секунд', + m: 'бір минут', + mm: '%d минут', + h: 'бір сағат', + hh: '%d сағат', + d: 'бір күн', + dd: '%d күн', + M: 'бір ай', + MM: '%d ай', + y: 'бір жыл', + yy: '%d жыл', + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/, + ordinal: function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return kk; + +}))); + + +/***/ }), + +/***/ 96870: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Cambodian [km] +//! author : Kruy Vanna : https://github.com/kruyvanna + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '១', + 2: '២', + 3: '៣', + 4: '៤', + 5: '៥', + 6: '៦', + 7: '៧', + 8: '៨', + 9: '៩', + 0: '០', + }, + numberMap = { + '១': '1', + '២': '2', + '៣': '3', + '៤': '4', + '៥': '5', + '៦': '6', + '៧': '7', + '៨': '8', + '៩': '9', + '០': '0', + }; + + var km = moment.defineLocale('km', { + months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( + '_' + ), + monthsShort: + 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( + '_' + ), + weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), + weekdaysShort: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), + weekdaysMin: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + meridiemParse: /ព្រឹក|ល្ងាច/, + isPM: function (input) { + return input === 'ល្ងាច'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ព្រឹក'; + } else { + return 'ល្ងាច'; + } + }, + calendar: { + sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', + nextDay: '[ស្អែក ម៉ោង] LT', + nextWeek: 'dddd [ម៉ោង] LT', + lastDay: '[ម្សិលមិញ ម៉ោង] LT', + lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%sទៀត', + past: '%sមុន', + s: 'ប៉ុន្មានវិនាទី', + ss: '%d វិនាទី', + m: 'មួយនាទី', + mm: '%d នាទី', + h: 'មួយម៉ោង', + hh: '%d ម៉ោង', + d: 'មួយថ្ងៃ', + dd: '%d ថ្ងៃ', + M: 'មួយខែ', + MM: '%d ខែ', + y: 'មួយឆ្នាំ', + yy: '%d ឆ្នាំ', + }, + dayOfMonthOrdinalParse: /ទី\d{1,2}/, + ordinal: 'ទី%d', + preparse: function (string) { + return string.replace(/[១២៣៤៥៦៧៨៩០]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return km; + +}))); + + +/***/ }), + +/***/ 84451: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Kannada [kn] +//! author : Rajeev Naik : https://github.com/rajeevnaikte + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '೧', + 2: '೨', + 3: '೩', + 4: '೪', + 5: '೫', + 6: '೬', + 7: '೭', + 8: '೮', + 9: '೯', + 0: '೦', + }, + numberMap = { + '೧': '1', + '೨': '2', + '೩': '3', + '೪': '4', + '೫': '5', + '೬': '6', + '೭': '7', + '೮': '8', + '೯': '9', + '೦': '0', + }; + + var kn = moment.defineLocale('kn', { + months: 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split( + '_' + ), + monthsShort: + 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split( + '_' + ), + weekdaysShort: 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), + weekdaysMin: 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), + longDateFormat: { + LT: 'A h:mm', + LTS: 'A h:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm', + LLLL: 'dddd, D MMMM YYYY, A h:mm', + }, + calendar: { + sameDay: '[ಇಂದು] LT', + nextDay: '[ನಾಳೆ] LT', + nextWeek: 'dddd, LT', + lastDay: '[ನಿನ್ನೆ] LT', + lastWeek: '[ಕೊನೆಯ] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s ನಂತರ', + past: '%s ಹಿಂದೆ', + s: 'ಕೆಲವು ಕ್ಷಣಗಳು', + ss: '%d ಸೆಕೆಂಡುಗಳು', + m: 'ಒಂದು ನಿಮಿಷ', + mm: '%d ನಿಮಿಷ', + h: 'ಒಂದು ಗಂಟೆ', + hh: '%d ಗಂಟೆ', + d: 'ಒಂದು ದಿನ', + dd: '%d ದಿನ', + M: 'ಒಂದು ತಿಂಗಳು', + MM: '%d ತಿಂಗಳು', + y: 'ಒಂದು ವರ್ಷ', + yy: '%d ವರ್ಷ', + }, + preparse: function (string) { + return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ರಾತ್ರಿ') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') { + return hour; + } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'ಸಂಜೆ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'ರಾತ್ರಿ'; + } else if (hour < 10) { + return 'ಬೆಳಿಗ್ಗೆ'; + } else if (hour < 17) { + return 'ಮಧ್ಯಾಹ್ನ'; + } else if (hour < 20) { + return 'ಸಂಜೆ'; + } else { + return 'ರಾತ್ರಿ'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/, + ordinal: function (number) { + return number + 'ನೇ'; + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return kn; + +}))); + + +/***/ }), + +/***/ 63164: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Korean [ko] +//! author : Kyungwook, Park : https://github.com/kyungw00k +//! author : Jeeeyul Lee + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ko = moment.defineLocale('ko', { + months: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), + monthsShort: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split( + '_' + ), + weekdays: '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), + weekdaysShort: '일_월_화_수_목_금_토'.split('_'), + weekdaysMin: '일_월_화_수_목_금_토'.split('_'), + longDateFormat: { + LT: 'A h:mm', + LTS: 'A h:mm:ss', + L: 'YYYY.MM.DD.', + LL: 'YYYY년 MMMM D일', + LLL: 'YYYY년 MMMM D일 A h:mm', + LLLL: 'YYYY년 MMMM D일 dddd A h:mm', + l: 'YYYY.MM.DD.', + ll: 'YYYY년 MMMM D일', + lll: 'YYYY년 MMMM D일 A h:mm', + llll: 'YYYY년 MMMM D일 dddd A h:mm', + }, + calendar: { + sameDay: '오늘 LT', + nextDay: '내일 LT', + nextWeek: 'dddd LT', + lastDay: '어제 LT', + lastWeek: '지난주 dddd LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s 후', + past: '%s 전', + s: '몇 초', + ss: '%d초', + m: '1분', + mm: '%d분', + h: '한 시간', + hh: '%d시간', + d: '하루', + dd: '%d일', + M: '한 달', + MM: '%d달', + y: '일 년', + yy: '%d년', + }, + dayOfMonthOrdinalParse: /\d{1,2}(일|월|주)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '일'; + case 'M': + return number + '월'; + case 'w': + case 'W': + return number + '주'; + default: + return number; + } + }, + meridiemParse: /오전|오후/, + isPM: function (token) { + return token === '오후'; + }, + meridiem: function (hour, minute, isUpper) { + return hour < 12 ? '오전' : '오후'; + }, + }); + + return ko; + +}))); + + +/***/ }), + +/***/ 6181: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Northern Kurdish [ku-kmr] +//! authors : Mazlum Özdogan : https://github.com/mergehez + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(num, withoutSuffix, key, isFuture) { + var format = { + s: ['çend sanîye', 'çend sanîyeyan'], + ss: [num + ' sanîye', num + ' sanîyeyan'], + m: ['deqîqeyek', 'deqîqeyekê'], + mm: [num + ' deqîqe', num + ' deqîqeyan'], + h: ['saetek', 'saetekê'], + hh: [num + ' saet', num + ' saetan'], + d: ['rojek', 'rojekê'], + dd: [num + ' roj', num + ' rojan'], + w: ['hefteyek', 'hefteyekê'], + ww: [num + ' hefte', num + ' hefteyan'], + M: ['mehek', 'mehekê'], + MM: [num + ' meh', num + ' mehan'], + y: ['salek', 'salekê'], + yy: [num + ' sal', num + ' salan'], + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + // function obliqueNumSuffix(num) { + // if(num.includes(':')) + // num = parseInt(num.split(':')[0]); + // else + // num = parseInt(num); + // return num == 0 || num % 10 == 1 ? 'ê' + // : (num > 10 && num % 10 == 0 ? 'î' : 'an'); + // } + function ezafeNumSuffix(num) { + num = '' + num; + var l = num.substring(num.length - 1), + ll = num.length > 1 ? num.substring(num.length - 2) : ''; + if ( + !(ll == 12 || ll == 13) && + (l == '2' || l == '3' || ll == '50' || l == '70' || l == '80') + ) + return 'yê'; + return 'ê'; + } + + var kuKmr = moment.defineLocale('ku-kmr', { + // According to the spelling rules defined by the work group of Weqfa Mezopotamyayê (Mesopotamia Foundation) + // this should be: 'Kanûna Paşîn_Sibat_Adar_Nîsan_Gulan_Hezîran_Tîrmeh_Tebax_Îlon_Çirîya Pêşîn_Çirîya Paşîn_Kanûna Pêşîn' + // But the names below are more well known and handy + months: 'Rêbendan_Sibat_Adar_Nîsan_Gulan_Hezîran_Tîrmeh_Tebax_Îlon_Cotmeh_Mijdar_Berfanbar'.split( + '_' + ), + monthsShort: 'Rêb_Sib_Ada_Nîs_Gul_Hez_Tîr_Teb_Îlo_Cot_Mij_Ber'.split('_'), + monthsParseExact: true, + weekdays: 'Yekşem_Duşem_Sêşem_Çarşem_Pêncşem_În_Şemî'.split('_'), + weekdaysShort: 'Yek_Du_Sê_Çar_Pên_În_Şem'.split('_'), + weekdaysMin: 'Ye_Du_Sê_Ça_Pê_În_Şe'.split('_'), + meridiem: function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'bn' : 'BN'; + } else { + return isLower ? 'pn' : 'PN'; + } + }, + meridiemParse: /bn|BN|pn|PN/, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'Do MMMM[a] YYYY[an]', + LLL: 'Do MMMM[a] YYYY[an] HH:mm', + LLLL: 'dddd, Do MMMM[a] YYYY[an] HH:mm', + ll: 'Do MMM[.] YYYY[an]', + lll: 'Do MMM[.] YYYY[an] HH:mm', + llll: 'ddd[.], Do MMM[.] YYYY[an] HH:mm', + }, + calendar: { + sameDay: '[Îro di saet] LT [de]', + nextDay: '[Sibê di saet] LT [de]', + nextWeek: 'dddd [di saet] LT [de]', + lastDay: '[Duh di saet] LT [de]', + lastWeek: 'dddd[a borî di saet] LT [de]', + sameElse: 'L', + }, + relativeTime: { + future: 'di %s de', + past: 'berî %s', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: processRelativeTime, + w: processRelativeTime, + ww: processRelativeTime, + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}(?:yê|ê|\.)/, + ordinal: function (num, period) { + var p = period.toLowerCase(); + if (p.includes('w') || p.includes('m')) return num + '.'; + + return num + ezafeNumSuffix(num); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return kuKmr; + +}))); + + +/***/ }), + +/***/ 98174: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Kurdish [ku] +//! author : Shahram Mebashar : https://github.com/ShahramMebashar + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '١', + 2: '٢', + 3: '٣', + 4: '٤', + 5: '٥', + 6: '٦', + 7: '٧', + 8: '٨', + 9: '٩', + 0: '٠', + }, + numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0', + }, + months = [ + 'کانونی دووەم', + 'شوبات', + 'ئازار', + 'نیسان', + 'ئایار', + 'حوزەیران', + 'تەمموز', + 'ئاب', + 'ئەیلوول', + 'تشرینی یەكەم', + 'تشرینی دووەم', + 'كانونی یەکەم', + ]; + + var ku = moment.defineLocale('ku', { + months: months, + monthsShort: months, + weekdays: + 'یه‌كشه‌ممه‌_دووشه‌ممه‌_سێشه‌ممه‌_چوارشه‌ممه‌_پێنجشه‌ممه‌_هه‌ینی_شه‌ممه‌'.split( + '_' + ), + weekdaysShort: + 'یه‌كشه‌م_دووشه‌م_سێشه‌م_چوارشه‌م_پێنجشه‌م_هه‌ینی_شه‌ممه‌'.split('_'), + weekdaysMin: 'ی_د_س_چ_پ_ه_ش'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + meridiemParse: /ئێواره‌|به‌یانی/, + isPM: function (input) { + return /ئێواره‌/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'به‌یانی'; + } else { + return 'ئێواره‌'; + } + }, + calendar: { + sameDay: '[ئه‌مرۆ كاتژمێر] LT', + nextDay: '[به‌یانی كاتژمێر] LT', + nextWeek: 'dddd [كاتژمێر] LT', + lastDay: '[دوێنێ كاتژمێر] LT', + lastWeek: 'dddd [كاتژمێر] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'له‌ %s', + past: '%s', + s: 'چه‌ند چركه‌یه‌ك', + ss: 'چركه‌ %d', + m: 'یه‌ك خوله‌ك', + mm: '%d خوله‌ك', + h: 'یه‌ك كاتژمێر', + hh: '%d كاتژمێر', + d: 'یه‌ك ڕۆژ', + dd: '%d ڕۆژ', + M: 'یه‌ك مانگ', + MM: '%d مانگ', + y: 'یه‌ك ساڵ', + yy: '%d ساڵ', + }, + preparse: function (string) { + return string + .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }) + .replace(/،/g, ','); + }, + postformat: function (string) { + return string + .replace(/\d/g, function (match) { + return symbolMap[match]; + }) + .replace(/,/g, '،'); + }, + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return ku; + +}))); + + +/***/ }), + +/***/ 78474: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Kyrgyz [ky] +//! author : Chyngyz Arystan uulu : https://github.com/chyngyz + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 0: '-чү', + 1: '-чи', + 2: '-чи', + 3: '-чү', + 4: '-чү', + 5: '-чи', + 6: '-чы', + 7: '-чи', + 8: '-чи', + 9: '-чу', + 10: '-чу', + 20: '-чы', + 30: '-чу', + 40: '-чы', + 50: '-чү', + 60: '-чы', + 70: '-чи', + 80: '-чи', + 90: '-чу', + 100: '-чү', + }; + + var ky = moment.defineLocale('ky', { + months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split( + '_' + ), + monthsShort: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split( + '_' + ), + weekdays: 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split( + '_' + ), + weekdaysShort: 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), + weekdaysMin: 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Бүгүн саат] LT', + nextDay: '[Эртең саат] LT', + nextWeek: 'dddd [саат] LT', + lastDay: '[Кечээ саат] LT', + lastWeek: '[Өткөн аптанын] dddd [күнү] [саат] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s ичинде', + past: '%s мурун', + s: 'бирнече секунд', + ss: '%d секунд', + m: 'бир мүнөт', + mm: '%d мүнөт', + h: 'бир саат', + hh: '%d саат', + d: 'бир күн', + dd: '%d күн', + M: 'бир ай', + MM: '%d ай', + y: 'бир жыл', + yy: '%d жыл', + }, + dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/, + ordinal: function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return ky; + +}))); + + +/***/ }), + +/***/ 79680: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Luxembourgish [lb] +//! author : mweimerskirch : https://github.com/mweimerskirch +//! author : David Raison : https://github.com/kwisatz + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + m: ['eng Minutt', 'enger Minutt'], + h: ['eng Stonn', 'enger Stonn'], + d: ['een Dag', 'engem Dag'], + M: ['ee Mount', 'engem Mount'], + y: ['ee Joer', 'engem Joer'], + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + function processFutureTime(string) { + var number = string.substr(0, string.indexOf(' ')); + if (eifelerRegelAppliesToNumber(number)) { + return 'a ' + string; + } + return 'an ' + string; + } + function processPastTime(string) { + var number = string.substr(0, string.indexOf(' ')); + if (eifelerRegelAppliesToNumber(number)) { + return 'viru ' + string; + } + return 'virun ' + string; + } + /** + * Returns true if the word before the given number loses the '-n' ending. + * e.g. 'an 10 Deeg' but 'a 5 Deeg' + * + * @param number {integer} + * @returns {boolean} + */ + function eifelerRegelAppliesToNumber(number) { + number = parseInt(number, 10); + if (isNaN(number)) { + return false; + } + if (number < 0) { + // Negative Number --> always true + return true; + } else if (number < 10) { + // Only 1 digit + if (4 <= number && number <= 7) { + return true; + } + return false; + } else if (number < 100) { + // 2 digits + var lastDigit = number % 10, + firstDigit = number / 10; + if (lastDigit === 0) { + return eifelerRegelAppliesToNumber(firstDigit); + } + return eifelerRegelAppliesToNumber(lastDigit); + } else if (number < 10000) { + // 3 or 4 digits --> recursively check first digit + while (number >= 10) { + number = number / 10; + } + return eifelerRegelAppliesToNumber(number); + } else { + // Anything larger than 4 digits: recursively check first n-3 digits + number = number / 1000; + return eifelerRegelAppliesToNumber(number); + } + } + + var lb = moment.defineLocale('lb', { + months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split( + '_' + ), + monthsShort: + 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split( + '_' + ), + weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), + weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm [Auer]', + LTS: 'H:mm:ss [Auer]', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm [Auer]', + LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]', + }, + calendar: { + sameDay: '[Haut um] LT', + sameElse: 'L', + nextDay: '[Muer um] LT', + nextWeek: 'dddd [um] LT', + lastDay: '[Gëschter um] LT', + lastWeek: function () { + // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule + switch (this.day()) { + case 2: + case 4: + return '[Leschten] dddd [um] LT'; + default: + return '[Leschte] dddd [um] LT'; + } + }, + }, + relativeTime: { + future: processFutureTime, + past: processPastTime, + s: 'e puer Sekonnen', + ss: '%d Sekonnen', + m: processRelativeTime, + mm: '%d Minutten', + h: processRelativeTime, + hh: '%d Stonnen', + d: processRelativeTime, + dd: '%d Deeg', + M: processRelativeTime, + MM: '%d Méint', + y: processRelativeTime, + yy: '%d Joer', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return lb; + +}))); + + +/***/ }), + +/***/ 15867: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Lao [lo] +//! author : Ryan Hart : https://github.com/ryanhart2 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var lo = moment.defineLocale('lo', { + months: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split( + '_' + ), + monthsShort: + 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split( + '_' + ), + weekdays: 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), + weekdaysShort: 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), + weekdaysMin: 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'ວັນdddd D MMMM YYYY HH:mm', + }, + meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, + isPM: function (input) { + return input === 'ຕອນແລງ'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ຕອນເຊົ້າ'; + } else { + return 'ຕອນແລງ'; + } + }, + calendar: { + sameDay: '[ມື້ນີ້ເວລາ] LT', + nextDay: '[ມື້ອື່ນເວລາ] LT', + nextWeek: '[ວັນ]dddd[ໜ້າເວລາ] LT', + lastDay: '[ມື້ວານນີ້ເວລາ] LT', + lastWeek: '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'ອີກ %s', + past: '%sຜ່ານມາ', + s: 'ບໍ່ເທົ່າໃດວິນາທີ', + ss: '%d ວິນາທີ', + m: '1 ນາທີ', + mm: '%d ນາທີ', + h: '1 ຊົ່ວໂມງ', + hh: '%d ຊົ່ວໂມງ', + d: '1 ມື້', + dd: '%d ມື້', + M: '1 ເດືອນ', + MM: '%d ເດືອນ', + y: '1 ປີ', + yy: '%d ປີ', + }, + dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/, + ordinal: function (number) { + return 'ທີ່' + number; + }, + }); + + return lo; + +}))); + + +/***/ }), + +/***/ 45766: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Lithuanian [lt] +//! author : Mindaugas Mozūras : https://github.com/mmozuras + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var units = { + ss: 'sekundė_sekundžių_sekundes', + m: 'minutė_minutės_minutę', + mm: 'minutės_minučių_minutes', + h: 'valanda_valandos_valandą', + hh: 'valandos_valandų_valandas', + d: 'diena_dienos_dieną', + dd: 'dienos_dienų_dienas', + M: 'mėnuo_mėnesio_mėnesį', + MM: 'mėnesiai_mėnesių_mėnesius', + y: 'metai_metų_metus', + yy: 'metai_metų_metus', + }; + function translateSeconds(number, withoutSuffix, key, isFuture) { + if (withoutSuffix) { + return 'kelios sekundės'; + } else { + return isFuture ? 'kelių sekundžių' : 'kelias sekundes'; + } + } + function translateSingular(number, withoutSuffix, key, isFuture) { + return withoutSuffix + ? forms(key)[0] + : isFuture + ? forms(key)[1] + : forms(key)[2]; + } + function special(number) { + return number % 10 === 0 || (number > 10 && number < 20); + } + function forms(key) { + return units[key].split('_'); + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + if (number === 1) { + return ( + result + translateSingular(number, withoutSuffix, key[0], isFuture) + ); + } else if (withoutSuffix) { + return result + (special(number) ? forms(key)[1] : forms(key)[0]); + } else { + if (isFuture) { + return result + forms(key)[1]; + } else { + return result + (special(number) ? forms(key)[1] : forms(key)[2]); + } + } + } + var lt = moment.defineLocale('lt', { + months: { + format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split( + '_' + ), + standalone: + 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split( + '_' + ), + isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/, + }, + monthsShort: 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), + weekdays: { + format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split( + '_' + ), + standalone: + 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split( + '_' + ), + isFormat: /dddd HH:mm/, + }, + weekdaysShort: 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), + weekdaysMin: 'S_P_A_T_K_Pn_Š'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'YYYY [m.] MMMM D [d.]', + LLL: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', + LLLL: 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', + l: 'YYYY-MM-DD', + ll: 'YYYY [m.] MMMM D [d.]', + lll: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', + llll: 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]', + }, + calendar: { + sameDay: '[Šiandien] LT', + nextDay: '[Rytoj] LT', + nextWeek: 'dddd LT', + lastDay: '[Vakar] LT', + lastWeek: '[Praėjusį] dddd LT', + sameElse: 'L', + }, + relativeTime: { + future: 'po %s', + past: 'prieš %s', + s: translateSeconds, + ss: translate, + m: translateSingular, + mm: translate, + h: translateSingular, + hh: translate, + d: translateSingular, + dd: translate, + M: translateSingular, + MM: translate, + y: translateSingular, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}-oji/, + ordinal: function (number) { + return number + '-oji'; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return lt; + +}))); + + +/***/ }), + +/***/ 69532: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Latvian [lv] +//! author : Kristaps Karlsons : https://github.com/skakri +//! author : Jānis Elmeris : https://github.com/JanisE + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var units = { + ss: 'sekundes_sekundēm_sekunde_sekundes'.split('_'), + m: 'minūtes_minūtēm_minūte_minūtes'.split('_'), + mm: 'minūtes_minūtēm_minūte_minūtes'.split('_'), + h: 'stundas_stundām_stunda_stundas'.split('_'), + hh: 'stundas_stundām_stunda_stundas'.split('_'), + d: 'dienas_dienām_diena_dienas'.split('_'), + dd: 'dienas_dienām_diena_dienas'.split('_'), + M: 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), + MM: 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), + y: 'gada_gadiem_gads_gadi'.split('_'), + yy: 'gada_gadiem_gads_gadi'.split('_'), + }; + /** + * @param withoutSuffix boolean true = a length of time; false = before/after a period of time. + */ + function format(forms, number, withoutSuffix) { + if (withoutSuffix) { + // E.g. "21 minūte", "3 minūtes". + return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3]; + } else { + // E.g. "21 minūtes" as in "pēc 21 minūtes". + // E.g. "3 minūtēm" as in "pēc 3 minūtēm". + return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1]; + } + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + return number + ' ' + format(units[key], number, withoutSuffix); + } + function relativeTimeWithSingular(number, withoutSuffix, key) { + return format(units[key], number, withoutSuffix); + } + function relativeSeconds(number, withoutSuffix) { + return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm'; + } + + var lv = moment.defineLocale('lv', { + months: 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split( + '_' + ), + monthsShort: 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), + weekdays: + 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split( + '_' + ), + weekdaysShort: 'Sv_P_O_T_C_Pk_S'.split('_'), + weekdaysMin: 'Sv_P_O_T_C_Pk_S'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY.', + LL: 'YYYY. [gada] D. MMMM', + LLL: 'YYYY. [gada] D. MMMM, HH:mm', + LLLL: 'YYYY. [gada] D. MMMM, dddd, HH:mm', + }, + calendar: { + sameDay: '[Šodien pulksten] LT', + nextDay: '[Rīt pulksten] LT', + nextWeek: 'dddd [pulksten] LT', + lastDay: '[Vakar pulksten] LT', + lastWeek: '[Pagājušā] dddd [pulksten] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'pēc %s', + past: 'pirms %s', + s: relativeSeconds, + ss: relativeTimeWithPlural, + m: relativeTimeWithSingular, + mm: relativeTimeWithPlural, + h: relativeTimeWithSingular, + hh: relativeTimeWithPlural, + d: relativeTimeWithSingular, + dd: relativeTimeWithPlural, + M: relativeTimeWithSingular, + MM: relativeTimeWithPlural, + y: relativeTimeWithSingular, + yy: relativeTimeWithPlural, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return lv; + +}))); + + +/***/ }), + +/***/ 58076: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Montenegrin [me] +//! author : Miodrag Nikač : https://github.com/miodragnikac + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var translator = { + words: { + //Different grammatical cases + ss: ['sekund', 'sekunda', 'sekundi'], + m: ['jedan minut', 'jednog minuta'], + mm: ['minut', 'minuta', 'minuta'], + h: ['jedan sat', 'jednog sata'], + hh: ['sat', 'sata', 'sati'], + dd: ['dan', 'dana', 'dana'], + MM: ['mjesec', 'mjeseca', 'mjeseci'], + yy: ['godina', 'godine', 'godina'], + }, + correctGrammaticalCase: function (number, wordKey) { + return number === 1 + ? wordKey[0] + : number >= 2 && number <= 4 + ? wordKey[1] + : wordKey[2]; + }, + translate: function (number, withoutSuffix, key) { + var wordKey = translator.words[key]; + if (key.length === 1) { + return withoutSuffix ? wordKey[0] : wordKey[1]; + } else { + return ( + number + + ' ' + + translator.correctGrammaticalCase(number, wordKey) + ); + } + }, + }; + + var me = moment.defineLocale('me', { + months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split( + '_' + ), + monthsShort: + 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split( + '_' + ), + weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[danas u] LT', + nextDay: '[sjutra u] LT', + + nextWeek: function () { + switch (this.day()) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay: '[juče u] LT', + lastWeek: function () { + var lastWeekDays = [ + '[prošle] [nedjelje] [u] LT', + '[prošlog] [ponedjeljka] [u] LT', + '[prošlog] [utorka] [u] LT', + '[prošle] [srijede] [u] LT', + '[prošlog] [četvrtka] [u] LT', + '[prošlog] [petka] [u] LT', + '[prošle] [subote] [u] LT', + ]; + return lastWeekDays[this.day()]; + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'prije %s', + s: 'nekoliko sekundi', + ss: translator.translate, + m: translator.translate, + mm: translator.translate, + h: translator.translate, + hh: translator.translate, + d: 'dan', + dd: translator.translate, + M: 'mjesec', + MM: translator.translate, + y: 'godinu', + yy: translator.translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return me; + +}))); + + +/***/ }), + +/***/ 41848: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Maori [mi] +//! author : John Corrigan : https://github.com/johnideal + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var mi = moment.defineLocale('mi', { + months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split( + '_' + ), + monthsShort: + 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split( + '_' + ), + monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i, + weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'), + weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), + weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [i] HH:mm', + LLLL: 'dddd, D MMMM YYYY [i] HH:mm', + }, + calendar: { + sameDay: '[i teie mahana, i] LT', + nextDay: '[apopo i] LT', + nextWeek: 'dddd [i] LT', + lastDay: '[inanahi i] LT', + lastWeek: 'dddd [whakamutunga i] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'i roto i %s', + past: '%s i mua', + s: 'te hēkona ruarua', + ss: '%d hēkona', + m: 'he meneti', + mm: '%d meneti', + h: 'te haora', + hh: '%d haora', + d: 'he ra', + dd: '%d ra', + M: 'he marama', + MM: '%d marama', + y: 'he tau', + yy: '%d tau', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return mi; + +}))); + + +/***/ }), + +/***/ 30306: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Macedonian [mk] +//! author : Borislav Mickov : https://github.com/B0k0 +//! author : Sashko Todorov : https://github.com/bkyceh + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var mk = moment.defineLocale('mk', { + months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split( + '_' + ), + monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), + weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split( + '_' + ), + weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'), + weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'D.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY H:mm', + LLLL: 'dddd, D MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[Денес во] LT', + nextDay: '[Утре во] LT', + nextWeek: '[Во] dddd [во] LT', + lastDay: '[Вчера во] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 6: + return '[Изминатата] dddd [во] LT'; + case 1: + case 2: + case 4: + case 5: + return '[Изминатиот] dddd [во] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'за %s', + past: 'пред %s', + s: 'неколку секунди', + ss: '%d секунди', + m: 'една минута', + mm: '%d минути', + h: 'еден час', + hh: '%d часа', + d: 'еден ден', + dd: '%d дена', + M: 'еден месец', + MM: '%d месеци', + y: 'една година', + yy: '%d години', + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, + ordinal: function (number) { + var lastDigit = number % 10, + last2Digits = number % 100; + if (number === 0) { + return number + '-ев'; + } else if (last2Digits === 0) { + return number + '-ен'; + } else if (last2Digits > 10 && last2Digits < 20) { + return number + '-ти'; + } else if (lastDigit === 1) { + return number + '-ви'; + } else if (lastDigit === 2) { + return number + '-ри'; + } else if (lastDigit === 7 || lastDigit === 8) { + return number + '-ми'; + } else { + return number + '-ти'; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return mk; + +}))); + + +/***/ }), + +/***/ 73739: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Malayalam [ml] +//! author : Floyd Pink : https://github.com/floydpink + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ml = moment.defineLocale('ml', { + months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split( + '_' + ), + monthsShort: + 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split( + '_' + ), + weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), + weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), + longDateFormat: { + LT: 'A h:mm -നു', + LTS: 'A h:mm:ss -നു', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm -നു', + LLLL: 'dddd, D MMMM YYYY, A h:mm -നു', + }, + calendar: { + sameDay: '[ഇന്ന്] LT', + nextDay: '[നാളെ] LT', + nextWeek: 'dddd, LT', + lastDay: '[ഇന്നലെ] LT', + lastWeek: '[കഴിഞ്ഞ] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s കഴിഞ്ഞ്', + past: '%s മുൻപ്', + s: 'അൽപ നിമിഷങ്ങൾ', + ss: '%d സെക്കൻഡ്', + m: 'ഒരു മിനിറ്റ്', + mm: '%d മിനിറ്റ്', + h: 'ഒരു മണിക്കൂർ', + hh: '%d മണിക്കൂർ', + d: 'ഒരു ദിവസം', + dd: '%d ദിവസം', + M: 'ഒരു മാസം', + MM: '%d മാസം', + y: 'ഒരു വർഷം', + yy: '%d വർഷം', + }, + meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ( + (meridiem === 'രാത്രി' && hour >= 4) || + meridiem === 'ഉച്ച കഴിഞ്ഞ്' || + meridiem === 'വൈകുന്നേരം' + ) { + return hour + 12; + } else { + return hour; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'രാത്രി'; + } else if (hour < 12) { + return 'രാവിലെ'; + } else if (hour < 17) { + return 'ഉച്ച കഴിഞ്ഞ്'; + } else if (hour < 20) { + return 'വൈകുന്നേരം'; + } else { + return 'രാത്രി'; + } + }, + }); + + return ml; + +}))); + + +/***/ }), + +/***/ 99053: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Mongolian [mn] +//! author : Javkhlantugs Nyamdorj : https://github.com/javkhaanj7 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function translate(number, withoutSuffix, key, isFuture) { + switch (key) { + case 's': + return withoutSuffix ? 'хэдхэн секунд' : 'хэдхэн секундын'; + case 'ss': + return number + (withoutSuffix ? ' секунд' : ' секундын'); + case 'm': + case 'mm': + return number + (withoutSuffix ? ' минут' : ' минутын'); + case 'h': + case 'hh': + return number + (withoutSuffix ? ' цаг' : ' цагийн'); + case 'd': + case 'dd': + return number + (withoutSuffix ? ' өдөр' : ' өдрийн'); + case 'M': + case 'MM': + return number + (withoutSuffix ? ' сар' : ' сарын'); + case 'y': + case 'yy': + return number + (withoutSuffix ? ' жил' : ' жилийн'); + default: + return number; + } + } + + var mn = moment.defineLocale('mn', { + months: 'Нэгдүгээр сар_Хоёрдугаар сар_Гуравдугаар сар_Дөрөвдүгээр сар_Тавдугаар сар_Зургадугаар сар_Долдугаар сар_Наймдугаар сар_Есдүгээр сар_Аравдугаар сар_Арван нэгдүгээр сар_Арван хоёрдугаар сар'.split( + '_' + ), + monthsShort: + '1 сар_2 сар_3 сар_4 сар_5 сар_6 сар_7 сар_8 сар_9 сар_10 сар_11 сар_12 сар'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'Ням_Даваа_Мягмар_Лхагва_Пүрэв_Баасан_Бямба'.split('_'), + weekdaysShort: 'Ням_Дав_Мяг_Лха_Пүр_Баа_Бям'.split('_'), + weekdaysMin: 'Ня_Да_Мя_Лх_Пү_Ба_Бя'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'YYYY оны MMMMын D', + LLL: 'YYYY оны MMMMын D HH:mm', + LLLL: 'dddd, YYYY оны MMMMын D HH:mm', + }, + meridiemParse: /ҮӨ|ҮХ/i, + isPM: function (input) { + return input === 'ҮХ'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ҮӨ'; + } else { + return 'ҮХ'; + } + }, + calendar: { + sameDay: '[Өнөөдөр] LT', + nextDay: '[Маргааш] LT', + nextWeek: '[Ирэх] dddd LT', + lastDay: '[Өчигдөр] LT', + lastWeek: '[Өнгөрсөн] dddd LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s дараа', + past: '%s өмнө', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2} өдөр/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + ' өдөр'; + default: + return number; + } + }, + }); + + return mn; + +}))); + + +/***/ }), + +/***/ 86169: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Marathi [mr] +//! author : Harshad Kale : https://github.com/kalehv +//! author : Vivek Athalye : https://github.com/vnathalye + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '१', + 2: '२', + 3: '३', + 4: '४', + 5: '५', + 6: '६', + 7: '७', + 8: '८', + 9: '९', + 0: '०', + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0', + }; + + function relativeTimeMr(number, withoutSuffix, string, isFuture) { + var output = ''; + if (withoutSuffix) { + switch (string) { + case 's': + output = 'काही सेकंद'; + break; + case 'ss': + output = '%d सेकंद'; + break; + case 'm': + output = 'एक मिनिट'; + break; + case 'mm': + output = '%d मिनिटे'; + break; + case 'h': + output = 'एक तास'; + break; + case 'hh': + output = '%d तास'; + break; + case 'd': + output = 'एक दिवस'; + break; + case 'dd': + output = '%d दिवस'; + break; + case 'M': + output = 'एक महिना'; + break; + case 'MM': + output = '%d महिने'; + break; + case 'y': + output = 'एक वर्ष'; + break; + case 'yy': + output = '%d वर्षे'; + break; + } + } else { + switch (string) { + case 's': + output = 'काही सेकंदां'; + break; + case 'ss': + output = '%d सेकंदां'; + break; + case 'm': + output = 'एका मिनिटा'; + break; + case 'mm': + output = '%d मिनिटां'; + break; + case 'h': + output = 'एका तासा'; + break; + case 'hh': + output = '%d तासां'; + break; + case 'd': + output = 'एका दिवसा'; + break; + case 'dd': + output = '%d दिवसां'; + break; + case 'M': + output = 'एका महिन्या'; + break; + case 'MM': + output = '%d महिन्यां'; + break; + case 'y': + output = 'एका वर्षा'; + break; + case 'yy': + output = '%d वर्षां'; + break; + } + } + return output.replace(/%d/i, number); + } + + var mr = moment.defineLocale('mr', { + months: 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split( + '_' + ), + monthsShort: + 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), + weekdaysShort: 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), + weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), + longDateFormat: { + LT: 'A h:mm वाजता', + LTS: 'A h:mm:ss वाजता', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm वाजता', + LLLL: 'dddd, D MMMM YYYY, A h:mm वाजता', + }, + calendar: { + sameDay: '[आज] LT', + nextDay: '[उद्या] LT', + nextWeek: 'dddd, LT', + lastDay: '[काल] LT', + lastWeek: '[मागील] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%sमध्ये', + past: '%sपूर्वी', + s: relativeTimeMr, + ss: relativeTimeMr, + m: relativeTimeMr, + mm: relativeTimeMr, + h: relativeTimeMr, + hh: relativeTimeMr, + d: relativeTimeMr, + dd: relativeTimeMr, + M: relativeTimeMr, + MM: relativeTimeMr, + y: relativeTimeMr, + yy: relativeTimeMr, + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /पहाटे|सकाळी|दुपारी|सायंकाळी|रात्री/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'पहाटे' || meridiem === 'सकाळी') { + return hour; + } else if ( + meridiem === 'दुपारी' || + meridiem === 'सायंकाळी' || + meridiem === 'रात्री' + ) { + return hour >= 12 ? hour : hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour >= 0 && hour < 6) { + return 'पहाटे'; + } else if (hour < 12) { + return 'सकाळी'; + } else if (hour < 17) { + return 'दुपारी'; + } else if (hour < 20) { + return 'सायंकाळी'; + } else { + return 'रात्री'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return mr; + +}))); + + +/***/ }), + +/***/ 92297: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Malay [ms-my] +//! note : DEPRECATED, the correct one is [ms] +//! author : Weldan Jamili : https://github.com/weldan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var msMy = moment.defineLocale('ms-my', { + months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), + weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), + weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), + weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [pukul] HH.mm', + LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', + }, + meridiemParse: /pagi|tengahari|petang|malam/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'tengahari') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'petang' || meridiem === 'malam') { + return hour + 12; + } + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'tengahari'; + } else if (hours < 19) { + return 'petang'; + } else { + return 'malam'; + } + }, + calendar: { + sameDay: '[Hari ini pukul] LT', + nextDay: '[Esok pukul] LT', + nextWeek: 'dddd [pukul] LT', + lastDay: '[Kelmarin pukul] LT', + lastWeek: 'dddd [lepas pukul] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dalam %s', + past: '%s yang lepas', + s: 'beberapa saat', + ss: '%d saat', + m: 'seminit', + mm: '%d minit', + h: 'sejam', + hh: '%d jam', + d: 'sehari', + dd: '%d hari', + M: 'sebulan', + MM: '%d bulan', + y: 'setahun', + yy: '%d tahun', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return msMy; + +}))); + + +/***/ }), + +/***/ 73386: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Malay [ms] +//! author : Weldan Jamili : https://github.com/weldan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ms = moment.defineLocale('ms', { + months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), + weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), + weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), + weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [pukul] HH.mm', + LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', + }, + meridiemParse: /pagi|tengahari|petang|malam/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'tengahari') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'petang' || meridiem === 'malam') { + return hour + 12; + } + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'tengahari'; + } else if (hours < 19) { + return 'petang'; + } else { + return 'malam'; + } + }, + calendar: { + sameDay: '[Hari ini pukul] LT', + nextDay: '[Esok pukul] LT', + nextWeek: 'dddd [pukul] LT', + lastDay: '[Kelmarin pukul] LT', + lastWeek: 'dddd [lepas pukul] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dalam %s', + past: '%s yang lepas', + s: 'beberapa saat', + ss: '%d saat', + m: 'seminit', + mm: '%d minit', + h: 'sejam', + hh: '%d jam', + d: 'sehari', + dd: '%d hari', + M: 'sebulan', + MM: '%d bulan', + y: 'setahun', + yy: '%d tahun', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return ms; + +}))); + + +/***/ }), + +/***/ 77075: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Maltese (Malta) [mt] +//! author : Alessandro Maruccia : https://github.com/alesma + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var mt = moment.defineLocale('mt', { + months: 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split( + '_' + ), + monthsShort: 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'), + weekdays: + 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split( + '_' + ), + weekdaysShort: 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'), + weekdaysMin: 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Illum fil-]LT', + nextDay: '[Għada fil-]LT', + nextWeek: 'dddd [fil-]LT', + lastDay: '[Il-bieraħ fil-]LT', + lastWeek: 'dddd [li għadda] [fil-]LT', + sameElse: 'L', + }, + relativeTime: { + future: 'f’ %s', + past: '%s ilu', + s: 'ftit sekondi', + ss: '%d sekondi', + m: 'minuta', + mm: '%d minuti', + h: 'siegħa', + hh: '%d siegħat', + d: 'ġurnata', + dd: '%d ġranet', + M: 'xahar', + MM: '%d xhur', + y: 'sena', + yy: '%d sni', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return mt; + +}))); + + +/***/ }), + +/***/ 72264: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Burmese [my] +//! author : Squar team, mysquar.com +//! author : David Rossellat : https://github.com/gholadr +//! author : Tin Aung Lin : https://github.com/thanyawzinmin + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '၁', + 2: '၂', + 3: '၃', + 4: '၄', + 5: '၅', + 6: '၆', + 7: '၇', + 8: '၈', + 9: '၉', + 0: '၀', + }, + numberMap = { + '၁': '1', + '၂': '2', + '၃': '3', + '၄': '4', + '၅': '5', + '၆': '6', + '၇': '7', + '၈': '8', + '၉': '9', + '၀': '0', + }; + + var my = moment.defineLocale('my', { + months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split( + '_' + ), + monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), + weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split( + '_' + ), + weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), + weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), + + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[ယနေ.] LT [မှာ]', + nextDay: '[မနက်ဖြန်] LT [မှာ]', + nextWeek: 'dddd LT [မှာ]', + lastDay: '[မနေ.က] LT [မှာ]', + lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', + sameElse: 'L', + }, + relativeTime: { + future: 'လာမည့် %s မှာ', + past: 'လွန်ခဲ့သော %s က', + s: 'စက္ကန်.အနည်းငယ်', + ss: '%d စက္ကန့်', + m: 'တစ်မိနစ်', + mm: '%d မိနစ်', + h: 'တစ်နာရီ', + hh: '%d နာရီ', + d: 'တစ်ရက်', + dd: '%d ရက်', + M: 'တစ်လ', + MM: '%d လ', + y: 'တစ်နှစ်', + yy: '%d နှစ်', + }, + preparse: function (string) { + return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return my; + +}))); + + +/***/ }), + +/***/ 22274: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Norwegian Bokmål [nb] +//! authors : Espen Hovlandsdal : https://github.com/rexxars +//! Sigurd Gartmann : https://github.com/sigurdga +//! Stephen Ramthun : https://github.com/stephenramthun + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var nb = moment.defineLocale('nb', { + months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split( + '_' + ), + monthsShort: + 'jan._feb._mars_apr._mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), + monthsParseExact: true, + weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), + weekdaysShort: 'sø._ma._ti._on._to._fr._lø.'.split('_'), + weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY [kl.] HH:mm', + LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm', + }, + calendar: { + sameDay: '[i dag kl.] LT', + nextDay: '[i morgen kl.] LT', + nextWeek: 'dddd [kl.] LT', + lastDay: '[i går kl.] LT', + lastWeek: '[forrige] dddd [kl.] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'om %s', + past: '%s siden', + s: 'noen sekunder', + ss: '%d sekunder', + m: 'ett minutt', + mm: '%d minutter', + h: 'én time', + hh: '%d timer', + d: 'én dag', + dd: '%d dager', + w: 'én uke', + ww: '%d uker', + M: 'én måned', + MM: '%d måneder', + y: 'ett år', + yy: '%d år', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return nb; + +}))); + + +/***/ }), + +/***/ 8235: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Nepalese [ne] +//! author : suvash : https://github.com/suvash + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '१', + 2: '२', + 3: '३', + 4: '४', + 5: '५', + 6: '६', + 7: '७', + 8: '८', + 9: '९', + 0: '०', + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0', + }; + + var ne = moment.defineLocale('ne', { + months: 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split( + '_' + ), + monthsShort: + 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split( + '_' + ), + weekdaysShort: 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), + weekdaysMin: 'आ._सो._मं._बु._बि._शु._श.'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'Aको h:mm बजे', + LTS: 'Aको h:mm:ss बजे', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, Aको h:mm बजे', + LLLL: 'dddd, D MMMM YYYY, Aको h:mm बजे', + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /राति|बिहान|दिउँसो|साँझ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'राति') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'बिहान') { + return hour; + } else if (meridiem === 'दिउँसो') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'साँझ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 3) { + return 'राति'; + } else if (hour < 12) { + return 'बिहान'; + } else if (hour < 16) { + return 'दिउँसो'; + } else if (hour < 20) { + return 'साँझ'; + } else { + return 'राति'; + } + }, + calendar: { + sameDay: '[आज] LT', + nextDay: '[भोलि] LT', + nextWeek: '[आउँदो] dddd[,] LT', + lastDay: '[हिजो] LT', + lastWeek: '[गएको] dddd[,] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%sमा', + past: '%s अगाडि', + s: 'केही क्षण', + ss: '%d सेकेण्ड', + m: 'एक मिनेट', + mm: '%d मिनेट', + h: 'एक घण्टा', + hh: '%d घण्टा', + d: 'एक दिन', + dd: '%d दिन', + M: 'एक महिना', + MM: '%d महिना', + y: 'एक बर्ष', + yy: '%d बर्ष', + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return ne; + +}))); + + +/***/ }), + +/***/ 43784: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Dutch (Belgium) [nl-be] +//! author : Joris Röling : https://github.com/jorisroling +//! author : Jacob Middag : https://github.com/middagj + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortWithDots = + 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), + monthsShortWithoutDots = + 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'), + monthsParse = [ + /^jan/i, + /^feb/i, + /^(maart|mrt\.?)$/i, + /^apr/i, + /^mei$/i, + /^jun[i.]?$/i, + /^jul[i.]?$/i, + /^aug/i, + /^sep/i, + /^okt/i, + /^nov/i, + /^dec/i, + ], + monthsRegex = + /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; + + var nlBe = moment.defineLocale('nl-be', { + months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, + + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, + monthsShortStrictRegex: + /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, + + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + + weekdays: + 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), + weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'), + weekdaysMin: 'zo_ma_di_wo_do_vr_za'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[vandaag om] LT', + nextDay: '[morgen om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[gisteren om] LT', + lastWeek: '[afgelopen] dddd [om] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'over %s', + past: '%s geleden', + s: 'een paar seconden', + ss: '%d seconden', + m: 'één minuut', + mm: '%d minuten', + h: 'één uur', + hh: '%d uur', + d: 'één dag', + dd: '%d dagen', + M: 'één maand', + MM: '%d maanden', + y: 'één jaar', + yy: '%d jaar', + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal: function (number) { + return ( + number + + (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de') + ); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return nlBe; + +}))); + + +/***/ }), + +/***/ 92572: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Dutch [nl] +//! author : Joris Röling : https://github.com/jorisroling +//! author : Jacob Middag : https://github.com/middagj + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsShortWithDots = + 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), + monthsShortWithoutDots = + 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'), + monthsParse = [ + /^jan/i, + /^feb/i, + /^(maart|mrt\.?)$/i, + /^apr/i, + /^mei$/i, + /^jun[i.]?$/i, + /^jul[i.]?$/i, + /^aug/i, + /^sep/i, + /^okt/i, + /^nov/i, + /^dec/i, + ], + monthsRegex = + /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; + + var nl = moment.defineLocale('nl', { + months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split( + '_' + ), + monthsShort: function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, + + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: + /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, + monthsShortStrictRegex: + /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, + + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + + weekdays: + 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), + weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'), + weekdaysMin: 'zo_ma_di_wo_do_vr_za'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD-MM-YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[vandaag om] LT', + nextDay: '[morgen om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[gisteren om] LT', + lastWeek: '[afgelopen] dddd [om] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'over %s', + past: '%s geleden', + s: 'een paar seconden', + ss: '%d seconden', + m: 'één minuut', + mm: '%d minuten', + h: 'één uur', + hh: '%d uur', + d: 'één dag', + dd: '%d dagen', + w: 'één week', + ww: '%d weken', + M: 'één maand', + MM: '%d maanden', + y: 'één jaar', + yy: '%d jaar', + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal: function (number) { + return ( + number + + (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de') + ); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return nl; + +}))); + + +/***/ }), + +/***/ 54566: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Nynorsk [nn] +//! authors : https://github.com/mechuwind +//! Stephen Ramthun : https://github.com/stephenramthun + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var nn = moment.defineLocale('nn', { + months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split( + '_' + ), + monthsShort: + 'jan._feb._mars_apr._mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), + monthsParseExact: true, + weekdays: 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), + weekdaysShort: 'su._må._ty._on._to._fr._lau.'.split('_'), + weekdaysMin: 'su_må_ty_on_to_fr_la'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY [kl.] H:mm', + LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm', + }, + calendar: { + sameDay: '[I dag klokka] LT', + nextDay: '[I morgon klokka] LT', + nextWeek: 'dddd [klokka] LT', + lastDay: '[I går klokka] LT', + lastWeek: '[Føregåande] dddd [klokka] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'om %s', + past: '%s sidan', + s: 'nokre sekund', + ss: '%d sekund', + m: 'eit minutt', + mm: '%d minutt', + h: 'ein time', + hh: '%d timar', + d: 'ein dag', + dd: '%d dagar', + w: 'ei veke', + ww: '%d veker', + M: 'ein månad', + MM: '%d månader', + y: 'eit år', + yy: '%d år', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return nn; + +}))); + + +/***/ }), + +/***/ 69330: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Occitan, lengadocian dialecte [oc-lnc] +//! author : Quentin PAGÈS : https://github.com/Quenty31 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ocLnc = moment.defineLocale('oc-lnc', { + months: { + standalone: + 'genièr_febrièr_març_abril_mai_junh_julhet_agost_setembre_octòbre_novembre_decembre'.split( + '_' + ), + format: "de genièr_de febrièr_de març_d'abril_de mai_de junh_de julhet_d'agost_de setembre_d'octòbre_de novembre_de decembre".split( + '_' + ), + isFormat: /D[oD]?(\s)+MMMM/, + }, + monthsShort: + 'gen._febr._març_abr._mai_junh_julh._ago._set._oct._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'dimenge_diluns_dimars_dimècres_dijòus_divendres_dissabte'.split( + '_' + ), + weekdaysShort: 'dg._dl._dm._dc._dj._dv._ds.'.split('_'), + weekdaysMin: 'dg_dl_dm_dc_dj_dv_ds'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM [de] YYYY', + ll: 'D MMM YYYY', + LLL: 'D MMMM [de] YYYY [a] H:mm', + lll: 'D MMM YYYY, H:mm', + LLLL: 'dddd D MMMM [de] YYYY [a] H:mm', + llll: 'ddd D MMM YYYY, H:mm', + }, + calendar: { + sameDay: '[uèi a] LT', + nextDay: '[deman a] LT', + nextWeek: 'dddd [a] LT', + lastDay: '[ièr a] LT', + lastWeek: 'dddd [passat a] LT', + sameElse: 'L', + }, + relativeTime: { + future: "d'aquí %s", + past: 'fa %s', + s: 'unas segondas', + ss: '%d segondas', + m: 'una minuta', + mm: '%d minutas', + h: 'una ora', + hh: '%d oras', + d: 'un jorn', + dd: '%d jorns', + M: 'un mes', + MM: '%d meses', + y: 'un an', + yy: '%d ans', + }, + dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, + ordinal: function (number, period) { + var output = + number === 1 + ? 'r' + : number === 2 + ? 'n' + : number === 3 + ? 'r' + : number === 4 + ? 't' + : 'è'; + if (period === 'w' || period === 'W') { + output = 'a'; + } + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, + }, + }); + + return ocLnc; + +}))); + + +/***/ }), + +/***/ 29849: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Punjabi (India) [pa-in] +//! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '੧', + 2: '੨', + 3: '੩', + 4: '੪', + 5: '੫', + 6: '੬', + 7: '੭', + 8: '੮', + 9: '੯', + 0: '੦', + }, + numberMap = { + '੧': '1', + '੨': '2', + '੩': '3', + '੪': '4', + '੫': '5', + '੬': '6', + '੭': '7', + '੮': '8', + '੯': '9', + '੦': '0', + }; + + var paIn = moment.defineLocale('pa-in', { + // There are months name as per Nanakshahi Calendar but they are not used as rigidly in modern Punjabi. + months: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split( + '_' + ), + monthsShort: + 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split( + '_' + ), + weekdays: 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split( + '_' + ), + weekdaysShort: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), + weekdaysMin: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), + longDateFormat: { + LT: 'A h:mm ਵਜੇ', + LTS: 'A h:mm:ss ਵਜੇ', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm ਵਜੇ', + LLLL: 'dddd, D MMMM YYYY, A h:mm ਵਜੇ', + }, + calendar: { + sameDay: '[ਅਜ] LT', + nextDay: '[ਕਲ] LT', + nextWeek: '[ਅਗਲਾ] dddd, LT', + lastDay: '[ਕਲ] LT', + lastWeek: '[ਪਿਛਲੇ] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s ਵਿੱਚ', + past: '%s ਪਿਛਲੇ', + s: 'ਕੁਝ ਸਕਿੰਟ', + ss: '%d ਸਕਿੰਟ', + m: 'ਇਕ ਮਿੰਟ', + mm: '%d ਮਿੰਟ', + h: 'ਇੱਕ ਘੰਟਾ', + hh: '%d ਘੰਟੇ', + d: 'ਇੱਕ ਦਿਨ', + dd: '%d ਦਿਨ', + M: 'ਇੱਕ ਮਹੀਨਾ', + MM: '%d ਮਹੀਨੇ', + y: 'ਇੱਕ ਸਾਲ', + yy: '%d ਸਾਲ', + }, + preparse: function (string) { + return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Punjabi notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. + meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ਰਾਤ') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ਸਵੇਰ') { + return hour; + } else if (meridiem === 'ਦੁਪਹਿਰ') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'ਸ਼ਾਮ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'ਰਾਤ'; + } else if (hour < 10) { + return 'ਸਵੇਰ'; + } else if (hour < 17) { + return 'ਦੁਪਹਿਰ'; + } else if (hour < 20) { + return 'ਸ਼ਾਮ'; + } else { + return 'ਰਾਤ'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return paIn; + +}))); + + +/***/ }), + +/***/ 94418: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Polish [pl] +//! author : Rafal Hirsz : https://github.com/evoL + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var monthsNominative = + 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split( + '_' + ), + monthsSubjective = + 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split( + '_' + ), + monthsParse = [ + /^sty/i, + /^lut/i, + /^mar/i, + /^kwi/i, + /^maj/i, + /^cze/i, + /^lip/i, + /^sie/i, + /^wrz/i, + /^paź/i, + /^lis/i, + /^gru/i, + ]; + function plural(n) { + return n % 10 < 5 && n % 10 > 1 && ~~(n / 10) % 10 !== 1; + } + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + return result + (plural(number) ? 'sekundy' : 'sekund'); + case 'm': + return withoutSuffix ? 'minuta' : 'minutę'; + case 'mm': + return result + (plural(number) ? 'minuty' : 'minut'); + case 'h': + return withoutSuffix ? 'godzina' : 'godzinę'; + case 'hh': + return result + (plural(number) ? 'godziny' : 'godzin'); + case 'ww': + return result + (plural(number) ? 'tygodnie' : 'tygodni'); + case 'MM': + return result + (plural(number) ? 'miesiące' : 'miesięcy'); + case 'yy': + return result + (plural(number) ? 'lata' : 'lat'); + } + } + + var pl = moment.defineLocale('pl', { + months: function (momentToFormat, format) { + if (!momentToFormat) { + return monthsNominative; + } else if (/D MMMM/.test(format)) { + return monthsSubjective[momentToFormat.month()]; + } else { + return monthsNominative[momentToFormat.month()]; + } + }, + monthsShort: 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays: + 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), + weekdaysShort: 'ndz_pon_wt_śr_czw_pt_sob'.split('_'), + weekdaysMin: 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Dziś o] LT', + nextDay: '[Jutro o] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[W niedzielę o] LT'; + + case 2: + return '[We wtorek o] LT'; + + case 3: + return '[W środę o] LT'; + + case 6: + return '[W sobotę o] LT'; + + default: + return '[W] dddd [o] LT'; + } + }, + lastDay: '[Wczoraj o] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[W zeszłą niedzielę o] LT'; + case 3: + return '[W zeszłą środę o] LT'; + case 6: + return '[W zeszłą sobotę o] LT'; + default: + return '[W zeszły] dddd [o] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: '%s temu', + s: 'kilka sekund', + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: '1 dzień', + dd: '%d dni', + w: 'tydzień', + ww: translate, + M: 'miesiąc', + MM: translate, + y: 'rok', + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return pl; + +}))); + + +/***/ }), + +/***/ 48303: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Portuguese (Brazil) [pt-br] +//! author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ptBr = moment.defineLocale('pt-br', { + months: 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split( + '_' + ), + monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), + weekdays: + 'domingo_segunda-feira_terça-feira_quarta-feira_quinta-feira_sexta-feira_sábado'.split( + '_' + ), + weekdaysShort: 'dom_seg_ter_qua_qui_sex_sáb'.split('_'), + weekdaysMin: 'do_2ª_3ª_4ª_5ª_6ª_sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY [às] HH:mm', + LLLL: 'dddd, D [de] MMMM [de] YYYY [às] HH:mm', + }, + calendar: { + sameDay: '[Hoje às] LT', + nextDay: '[Amanhã às] LT', + nextWeek: 'dddd [às] LT', + lastDay: '[Ontem às] LT', + lastWeek: function () { + return this.day() === 0 || this.day() === 6 + ? '[Último] dddd [às] LT' // Saturday + Sunday + : '[Última] dddd [às] LT'; // Monday - Friday + }, + sameElse: 'L', + }, + relativeTime: { + future: 'em %s', + past: 'há %s', + s: 'poucos segundos', + ss: '%d segundos', + m: 'um minuto', + mm: '%d minutos', + h: 'uma hora', + hh: '%d horas', + d: 'um dia', + dd: '%d dias', + M: 'um mês', + MM: '%d meses', + y: 'um ano', + yy: '%d anos', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + invalidDate: 'Data inválida', + }); + + return ptBr; + +}))); + + +/***/ }), + +/***/ 79834: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Portuguese [pt] +//! author : Jefferson : https://github.com/jalex79 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var pt = moment.defineLocale('pt', { + months: 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split( + '_' + ), + monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), + weekdays: + 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split( + '_' + ), + weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), + weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D [de] MMMM [de] YYYY', + LLL: 'D [de] MMMM [de] YYYY HH:mm', + LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm', + }, + calendar: { + sameDay: '[Hoje às] LT', + nextDay: '[Amanhã às] LT', + nextWeek: 'dddd [às] LT', + lastDay: '[Ontem às] LT', + lastWeek: function () { + return this.day() === 0 || this.day() === 6 + ? '[Último] dddd [às] LT' // Saturday + Sunday + : '[Última] dddd [às] LT'; // Monday - Friday + }, + sameElse: 'L', + }, + relativeTime: { + future: 'em %s', + past: 'há %s', + s: 'segundos', + ss: '%d segundos', + m: 'um minuto', + mm: '%d minutos', + h: 'uma hora', + hh: '%d horas', + d: 'um dia', + dd: '%d dias', + w: 'uma semana', + ww: '%d semanas', + M: 'um mês', + MM: '%d meses', + y: 'um ano', + yy: '%d anos', + }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return pt; + +}))); + + +/***/ }), + +/***/ 24457: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Romanian [ro] +//! author : Vlad Gurdiga : https://github.com/gurdiga +//! author : Valentin Agachi : https://github.com/avaly +//! author : Emanuel Cepoi : https://github.com/cepem + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + ss: 'secunde', + mm: 'minute', + hh: 'ore', + dd: 'zile', + ww: 'săptămâni', + MM: 'luni', + yy: 'ani', + }, + separator = ' '; + if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { + separator = ' de '; + } + return number + separator + format[key]; + } + + var ro = moment.defineLocale('ro', { + months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split( + '_' + ), + monthsShort: + 'ian._feb._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), + weekdaysShort: 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), + weekdaysMin: 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY H:mm', + LLLL: 'dddd, D MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[azi la] LT', + nextDay: '[mâine la] LT', + nextWeek: 'dddd [la] LT', + lastDay: '[ieri la] LT', + lastWeek: '[fosta] dddd [la] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'peste %s', + past: '%s în urmă', + s: 'câteva secunde', + ss: relativeTimeWithPlural, + m: 'un minut', + mm: relativeTimeWithPlural, + h: 'o oră', + hh: relativeTimeWithPlural, + d: 'o zi', + dd: relativeTimeWithPlural, + w: 'o săptămână', + ww: relativeTimeWithPlural, + M: 'o lună', + MM: relativeTimeWithPlural, + y: 'un an', + yy: relativeTimeWithPlural, + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return ro; + +}))); + + +/***/ }), + +/***/ 82271: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Russian [ru] +//! author : Viktorminator : https://github.com/Viktorminator +//! author : Menelion Elensúle : https://github.com/Oire +//! author : Коренберг Марк : https://github.com/socketpair + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 + ? forms[0] + : num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) + ? forms[1] + : forms[2]; + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + ss: withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', + mm: withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', + hh: 'час_часа_часов', + dd: 'день_дня_дней', + ww: 'неделя_недели_недель', + MM: 'месяц_месяца_месяцев', + yy: 'год_года_лет', + }; + if (key === 'm') { + return withoutSuffix ? 'минута' : 'минуту'; + } else { + return number + ' ' + plural(format[key], +number); + } + } + var monthsParse = [ + /^янв/i, + /^фев/i, + /^мар/i, + /^апр/i, + /^ма[йя]/i, + /^июн/i, + /^июл/i, + /^авг/i, + /^сен/i, + /^окт/i, + /^ноя/i, + /^дек/i, + ]; + + // http://new.gramota.ru/spravka/rules/139-prop : § 103 + // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 + // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 + var ru = moment.defineLocale('ru', { + months: { + format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split( + '_' + ), + standalone: + 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split( + '_' + ), + }, + monthsShort: { + // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку? + format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split( + '_' + ), + standalone: + 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split( + '_' + ), + }, + weekdays: { + standalone: + 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split( + '_' + ), + format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split( + '_' + ), + isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?] ?dddd/, + }, + weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), + weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + + // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки + monthsRegex: + /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, + + // копия предыдущего + monthsShortRegex: + /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, + + // полные названия с падежами + monthsStrictRegex: + /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, + + // Выражение, которое соответствует только сокращённым формам + monthsShortStrictRegex: + /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY г.', + LLL: 'D MMMM YYYY г., H:mm', + LLLL: 'dddd, D MMMM YYYY г., H:mm', + }, + calendar: { + sameDay: '[Сегодня, в] LT', + nextDay: '[Завтра, в] LT', + lastDay: '[Вчера, в] LT', + nextWeek: function (now) { + if (now.week() !== this.week()) { + switch (this.day()) { + case 0: + return '[В следующее] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В следующий] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В следующую] dddd, [в] LT'; + } + } else { + if (this.day() === 2) { + return '[Во] dddd, [в] LT'; + } else { + return '[В] dddd, [в] LT'; + } + } + }, + lastWeek: function (now) { + if (now.week() !== this.week()) { + switch (this.day()) { + case 0: + return '[В прошлое] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В прошлый] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В прошлую] dddd, [в] LT'; + } + } else { + if (this.day() === 2) { + return '[Во] dddd, [в] LT'; + } else { + return '[В] dddd, [в] LT'; + } + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'через %s', + past: '%s назад', + s: 'несколько секунд', + ss: relativeTimeWithPlural, + m: relativeTimeWithPlural, + mm: relativeTimeWithPlural, + h: 'час', + hh: relativeTimeWithPlural, + d: 'день', + dd: relativeTimeWithPlural, + w: 'неделя', + ww: relativeTimeWithPlural, + M: 'месяц', + MM: relativeTimeWithPlural, + y: 'год', + yy: relativeTimeWithPlural, + }, + meridiemParse: /ночи|утра|дня|вечера/i, + isPM: function (input) { + return /^(дня|вечера)$/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'ночи'; + } else if (hour < 12) { + return 'утра'; + } else if (hour < 17) { + return 'дня'; + } else { + return 'вечера'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + return number + '-й'; + case 'D': + return number + '-го'; + case 'w': + case 'W': + return number + '-я'; + default: + return number; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return ru; + +}))); + + +/***/ }), + +/***/ 1221: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Sindhi [sd] +//! author : Narain Sagar : https://github.com/narainsagar + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = [ + 'جنوري', + 'فيبروري', + 'مارچ', + 'اپريل', + 'مئي', + 'جون', + 'جولاءِ', + 'آگسٽ', + 'سيپٽمبر', + 'آڪٽوبر', + 'نومبر', + 'ڊسمبر', + ], + days = ['آچر', 'سومر', 'اڱارو', 'اربع', 'خميس', 'جمع', 'ڇنڇر']; + + var sd = moment.defineLocale('sd', { + months: months, + monthsShort: months, + weekdays: days, + weekdaysShort: days, + weekdaysMin: days, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd، D MMMM YYYY HH:mm', + }, + meridiemParse: /صبح|شام/, + isPM: function (input) { + return 'شام' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'صبح'; + } + return 'شام'; + }, + calendar: { + sameDay: '[اڄ] LT', + nextDay: '[سڀاڻي] LT', + nextWeek: 'dddd [اڳين هفتي تي] LT', + lastDay: '[ڪالهه] LT', + lastWeek: '[گزريل هفتي] dddd [تي] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s پوء', + past: '%s اڳ', + s: 'چند سيڪنڊ', + ss: '%d سيڪنڊ', + m: 'هڪ منٽ', + mm: '%d منٽ', + h: 'هڪ ڪلاڪ', + hh: '%d ڪلاڪ', + d: 'هڪ ڏينهن', + dd: '%d ڏينهن', + M: 'هڪ مهينو', + MM: '%d مهينا', + y: 'هڪ سال', + yy: '%d سال', + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return sd; + +}))); + + +/***/ }), + +/***/ 33478: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Northern Sami [se] +//! authors : Bård Rolstad Henriksen : https://github.com/karamell + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var se = moment.defineLocale('se', { + months: 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split( + '_' + ), + monthsShort: + 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), + weekdays: + 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split( + '_' + ), + weekdaysShort: 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), + weekdaysMin: 's_v_m_g_d_b_L'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'MMMM D. [b.] YYYY', + LLL: 'MMMM D. [b.] YYYY [ti.] HH:mm', + LLLL: 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm', + }, + calendar: { + sameDay: '[otne ti] LT', + nextDay: '[ihttin ti] LT', + nextWeek: 'dddd [ti] LT', + lastDay: '[ikte ti] LT', + lastWeek: '[ovddit] dddd [ti] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s geažes', + past: 'maŋit %s', + s: 'moadde sekunddat', + ss: '%d sekunddat', + m: 'okta minuhta', + mm: '%d minuhtat', + h: 'okta diimmu', + hh: '%d diimmut', + d: 'okta beaivi', + dd: '%d beaivvit', + M: 'okta mánnu', + MM: '%d mánut', + y: 'okta jahki', + yy: '%d jagit', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return se; + +}))); + + +/***/ }), + +/***/ 17538: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Sinhalese [si] +//! author : Sampath Sitinamaluwa : https://github.com/sampathsris + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + /*jshint -W100*/ + var si = moment.defineLocale('si', { + months: 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split( + '_' + ), + monthsShort: 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split( + '_' + ), + weekdays: + 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split( + '_' + ), + weekdaysShort: 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'), + weekdaysMin: 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'a h:mm', + LTS: 'a h:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY MMMM D', + LLL: 'YYYY MMMM D, a h:mm', + LLLL: 'YYYY MMMM D [වැනි] dddd, a h:mm:ss', + }, + calendar: { + sameDay: '[අද] LT[ට]', + nextDay: '[හෙට] LT[ට]', + nextWeek: 'dddd LT[ට]', + lastDay: '[ඊයේ] LT[ට]', + lastWeek: '[පසුගිය] dddd LT[ට]', + sameElse: 'L', + }, + relativeTime: { + future: '%sකින්', + past: '%sකට පෙර', + s: 'තත්පර කිහිපය', + ss: 'තත්පර %d', + m: 'මිනිත්තුව', + mm: 'මිනිත්තු %d', + h: 'පැය', + hh: 'පැය %d', + d: 'දිනය', + dd: 'දින %d', + M: 'මාසය', + MM: 'මාස %d', + y: 'වසර', + yy: 'වසර %d', + }, + dayOfMonthOrdinalParse: /\d{1,2} වැනි/, + ordinal: function (number) { + return number + ' වැනි'; + }, + meridiemParse: /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, + isPM: function (input) { + return input === 'ප.ව.' || input === 'පස් වරු'; + }, + meridiem: function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'ප.ව.' : 'පස් වරු'; + } else { + return isLower ? 'පෙ.ව.' : 'පෙර වරු'; + } + }, + }); + + return si; + +}))); + + +/***/ }), + +/***/ 5784: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Slovak [sk] +//! author : Martin Minka : https://github.com/k2s +//! based on work of petrbela : https://github.com/petrbela + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = + 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split( + '_' + ), + monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); + function plural(n) { + return n > 1 && n < 5; + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': // a few seconds / in a few seconds / a few seconds ago + return withoutSuffix || isFuture ? 'pár sekúnd' : 'pár sekundami'; + case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'sekundy' : 'sekúnd'); + } else { + return result + 'sekundami'; + } + case 'm': // a minute / in a minute / a minute ago + return withoutSuffix ? 'minúta' : isFuture ? 'minútu' : 'minútou'; + case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'minúty' : 'minút'); + } else { + return result + 'minútami'; + } + case 'h': // an hour / in an hour / an hour ago + return withoutSuffix ? 'hodina' : isFuture ? 'hodinu' : 'hodinou'; + case 'hh': // 9 hours / in 9 hours / 9 hours ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'hodiny' : 'hodín'); + } else { + return result + 'hodinami'; + } + case 'd': // a day / in a day / a day ago + return withoutSuffix || isFuture ? 'deň' : 'dňom'; + case 'dd': // 9 days / in 9 days / 9 days ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'dni' : 'dní'); + } else { + return result + 'dňami'; + } + case 'M': // a month / in a month / a month ago + return withoutSuffix || isFuture ? 'mesiac' : 'mesiacom'; + case 'MM': // 9 months / in 9 months / 9 months ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'mesiace' : 'mesiacov'); + } else { + return result + 'mesiacmi'; + } + case 'y': // a year / in a year / a year ago + return withoutSuffix || isFuture ? 'rok' : 'rokom'; + case 'yy': // 9 years / in 9 years / 9 years ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'roky' : 'rokov'); + } else { + return result + 'rokmi'; + } + } + } + + var sk = moment.defineLocale('sk', { + months: months, + monthsShort: monthsShort, + weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), + weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'), + weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'), + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd D. MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[dnes o] LT', + nextDay: '[zajtra o] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[v nedeľu o] LT'; + case 1: + case 2: + return '[v] dddd [o] LT'; + case 3: + return '[v stredu o] LT'; + case 4: + return '[vo štvrtok o] LT'; + case 5: + return '[v piatok o] LT'; + case 6: + return '[v sobotu o] LT'; + } + }, + lastDay: '[včera o] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[minulú nedeľu o] LT'; + case 1: + case 2: + return '[minulý] dddd [o] LT'; + case 3: + return '[minulú stredu o] LT'; + case 4: + case 5: + return '[minulý] dddd [o] LT'; + case 6: + return '[minulú sobotu o] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'pred %s', + s: translate, + ss: translate, + m: translate, + mm: translate, + h: translate, + hh: translate, + d: translate, + dd: translate, + M: translate, + MM: translate, + y: translate, + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return sk; + +}))); + + +/***/ }), + +/***/ 46637: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Slovenian [sl] +//! author : Robert Sedovšek : https://github.com/sedovsek + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': + return withoutSuffix || isFuture + ? 'nekaj sekund' + : 'nekaj sekundami'; + case 'ss': + if (number === 1) { + result += withoutSuffix ? 'sekundo' : 'sekundi'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah'; + } else { + result += 'sekund'; + } + return result; + case 'm': + return withoutSuffix ? 'ena minuta' : 'eno minuto'; + case 'mm': + if (number === 1) { + result += withoutSuffix ? 'minuta' : 'minuto'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'minuti' : 'minutama'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'minute' : 'minutami'; + } else { + result += withoutSuffix || isFuture ? 'minut' : 'minutami'; + } + return result; + case 'h': + return withoutSuffix ? 'ena ura' : 'eno uro'; + case 'hh': + if (number === 1) { + result += withoutSuffix ? 'ura' : 'uro'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'uri' : 'urama'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'ure' : 'urami'; + } else { + result += withoutSuffix || isFuture ? 'ur' : 'urami'; + } + return result; + case 'd': + return withoutSuffix || isFuture ? 'en dan' : 'enim dnem'; + case 'dd': + if (number === 1) { + result += withoutSuffix || isFuture ? 'dan' : 'dnem'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'dni' : 'dnevoma'; + } else { + result += withoutSuffix || isFuture ? 'dni' : 'dnevi'; + } + return result; + case 'M': + return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem'; + case 'MM': + if (number === 1) { + result += withoutSuffix || isFuture ? 'mesec' : 'mesecem'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'meseca' : 'mesecema'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'mesece' : 'meseci'; + } else { + result += withoutSuffix || isFuture ? 'mesecev' : 'meseci'; + } + return result; + case 'y': + return withoutSuffix || isFuture ? 'eno leto' : 'enim letom'; + case 'yy': + if (number === 1) { + result += withoutSuffix || isFuture ? 'leto' : 'letom'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'leti' : 'letoma'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'leta' : 'leti'; + } else { + result += withoutSuffix || isFuture ? 'let' : 'leti'; + } + return result; + } + } + + var sl = moment.defineLocale('sl', { + months: 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split( + '_' + ), + monthsShort: + 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), + weekdaysShort: 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), + weekdaysMin: 'ne_po_to_sr_če_pe_so'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD. MM. YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm', + }, + calendar: { + sameDay: '[danes ob] LT', + nextDay: '[jutri ob] LT', + + nextWeek: function () { + switch (this.day()) { + case 0: + return '[v] [nedeljo] [ob] LT'; + case 3: + return '[v] [sredo] [ob] LT'; + case 6: + return '[v] [soboto] [ob] LT'; + case 1: + case 2: + case 4: + case 5: + return '[v] dddd [ob] LT'; + } + }, + lastDay: '[včeraj ob] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[prejšnjo] [nedeljo] [ob] LT'; + case 3: + return '[prejšnjo] [sredo] [ob] LT'; + case 6: + return '[prejšnjo] [soboto] [ob] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prejšnji] dddd [ob] LT'; + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'čez %s', + past: 'pred %s', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: processRelativeTime, + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return sl; + +}))); + + +/***/ }), + +/***/ 86794: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Albanian [sq] +//! author : Flakërim Ismani : https://github.com/flakerimi +//! author : Menelion Elensúle : https://github.com/Oire +//! author : Oerd Cukalla : https://github.com/oerd + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var sq = moment.defineLocale('sq', { + months: 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split( + '_' + ), + monthsShort: 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), + weekdays: 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split( + '_' + ), + weekdaysShort: 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), + weekdaysMin: 'D_H_Ma_Më_E_P_Sh'.split('_'), + weekdaysParseExact: true, + meridiemParse: /PD|MD/, + isPM: function (input) { + return input.charAt(0) === 'M'; + }, + meridiem: function (hours, minutes, isLower) { + return hours < 12 ? 'PD' : 'MD'; + }, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Sot në] LT', + nextDay: '[Nesër në] LT', + nextWeek: 'dddd [në] LT', + lastDay: '[Dje në] LT', + lastWeek: 'dddd [e kaluar në] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'në %s', + past: '%s më parë', + s: 'disa sekonda', + ss: '%d sekonda', + m: 'një minutë', + mm: '%d minuta', + h: 'një orë', + hh: '%d orë', + d: 'një ditë', + dd: '%d ditë', + M: 'një muaj', + MM: '%d muaj', + y: 'një vit', + yy: '%d vite', + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return sq; + +}))); + + +/***/ }), + +/***/ 3322: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Serbian Cyrillic [sr-cyrl] +//! author : Milan Janačković : https://github.com/milan-j +//! author : Stefan Crnjaković : https://github.com/crnjakovic + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var translator = { + words: { + //Different grammatical cases + ss: ['секунда', 'секунде', 'секунди'], + m: ['један минут', 'једног минута'], + mm: ['минут', 'минута', 'минута'], + h: ['један сат', 'једног сата'], + hh: ['сат', 'сата', 'сати'], + d: ['један дан', 'једног дана'], + dd: ['дан', 'дана', 'дана'], + M: ['један месец', 'једног месеца'], + MM: ['месец', 'месеца', 'месеци'], + y: ['једну годину', 'једне године'], + yy: ['годину', 'године', 'година'], + }, + correctGrammaticalCase: function (number, wordKey) { + if ( + number % 10 >= 1 && + number % 10 <= 4 && + (number % 100 < 10 || number % 100 >= 20) + ) { + return number % 10 === 1 ? wordKey[0] : wordKey[1]; + } + return wordKey[2]; + }, + translate: function (number, withoutSuffix, key, isFuture) { + var wordKey = translator.words[key], + word; + + if (key.length === 1) { + // Nominativ + if (key === 'y' && withoutSuffix) return 'једна година'; + return isFuture || withoutSuffix ? wordKey[0] : wordKey[1]; + } + + word = translator.correctGrammaticalCase(number, wordKey); + // Nominativ + if (key === 'yy' && withoutSuffix && word === 'годину') { + return number + ' година'; + } + + return number + ' ' + word; + }, + }; + + var srCyrl = moment.defineLocale('sr-cyrl', { + months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split( + '_' + ), + monthsShort: + 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), + monthsParseExact: true, + weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), + weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), + weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'D. M. YYYY.', + LL: 'D. MMMM YYYY.', + LLL: 'D. MMMM YYYY. H:mm', + LLLL: 'dddd, D. MMMM YYYY. H:mm', + }, + calendar: { + sameDay: '[данас у] LT', + nextDay: '[сутра у] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[у] [недељу] [у] LT'; + case 3: + return '[у] [среду] [у] LT'; + case 6: + return '[у] [суботу] [у] LT'; + case 1: + case 2: + case 4: + case 5: + return '[у] dddd [у] LT'; + } + }, + lastDay: '[јуче у] LT', + lastWeek: function () { + var lastWeekDays = [ + '[прошле] [недеље] [у] LT', + '[прошлог] [понедељка] [у] LT', + '[прошлог] [уторка] [у] LT', + '[прошле] [среде] [у] LT', + '[прошлог] [четвртка] [у] LT', + '[прошлог] [петка] [у] LT', + '[прошле] [суботе] [у] LT', + ]; + return lastWeekDays[this.day()]; + }, + sameElse: 'L', + }, + relativeTime: { + future: 'за %s', + past: 'пре %s', + s: 'неколико секунди', + ss: translator.translate, + m: translator.translate, + mm: translator.translate, + h: translator.translate, + hh: translator.translate, + d: translator.translate, + dd: translator.translate, + M: translator.translate, + MM: translator.translate, + y: translator.translate, + yy: translator.translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 1st is the first week of the year. + }, + }); + + return srCyrl; + +}))); + + +/***/ }), + +/***/ 45719: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Serbian [sr] +//! author : Milan Janačković : https://github.com/milan-j +//! author : Stefan Crnjaković : https://github.com/crnjakovic + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var translator = { + words: { + //Different grammatical cases + ss: ['sekunda', 'sekunde', 'sekundi'], + m: ['jedan minut', 'jednog minuta'], + mm: ['minut', 'minuta', 'minuta'], + h: ['jedan sat', 'jednog sata'], + hh: ['sat', 'sata', 'sati'], + d: ['jedan dan', 'jednog dana'], + dd: ['dan', 'dana', 'dana'], + M: ['jedan mesec', 'jednog meseca'], + MM: ['mesec', 'meseca', 'meseci'], + y: ['jednu godinu', 'jedne godine'], + yy: ['godinu', 'godine', 'godina'], + }, + correctGrammaticalCase: function (number, wordKey) { + if ( + number % 10 >= 1 && + number % 10 <= 4 && + (number % 100 < 10 || number % 100 >= 20) + ) { + return number % 10 === 1 ? wordKey[0] : wordKey[1]; + } + return wordKey[2]; + }, + translate: function (number, withoutSuffix, key, isFuture) { + var wordKey = translator.words[key], + word; + + if (key.length === 1) { + // Nominativ + if (key === 'y' && withoutSuffix) return 'jedna godina'; + return isFuture || withoutSuffix ? wordKey[0] : wordKey[1]; + } + + word = translator.correctGrammaticalCase(number, wordKey); + // Nominativ + if (key === 'yy' && withoutSuffix && word === 'godinu') { + return number + ' godina'; + } + + return number + ' ' + word; + }, + }; + + var sr = moment.defineLocale('sr', { + months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split( + '_' + ), + monthsShort: + 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split( + '_' + ), + weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'D. M. YYYY.', + LL: 'D. MMMM YYYY.', + LLL: 'D. MMMM YYYY. H:mm', + LLLL: 'dddd, D. MMMM YYYY. H:mm', + }, + calendar: { + sameDay: '[danas u] LT', + nextDay: '[sutra u] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[u] [nedelju] [u] LT'; + case 3: + return '[u] [sredu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay: '[juče u] LT', + lastWeek: function () { + var lastWeekDays = [ + '[prošle] [nedelje] [u] LT', + '[prošlog] [ponedeljka] [u] LT', + '[prošlog] [utorka] [u] LT', + '[prošle] [srede] [u] LT', + '[prošlog] [četvrtka] [u] LT', + '[prošlog] [petka] [u] LT', + '[prošle] [subote] [u] LT', + ]; + return lastWeekDays[this.day()]; + }, + sameElse: 'L', + }, + relativeTime: { + future: 'za %s', + past: 'pre %s', + s: 'nekoliko sekundi', + ss: translator.translate, + m: translator.translate, + mm: translator.translate, + h: translator.translate, + hh: translator.translate, + d: translator.translate, + dd: translator.translate, + M: translator.translate, + MM: translator.translate, + y: translator.translate, + yy: translator.translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return sr; + +}))); + + +/***/ }), + +/***/ 56000: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : siSwati [ss] +//! author : Nicolai Davies : https://github.com/nicolaidavies + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ss = moment.defineLocale('ss', { + months: "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split( + '_' + ), + monthsShort: 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), + weekdays: + 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split( + '_' + ), + weekdaysShort: 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), + weekdaysMin: 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendar: { + sameDay: '[Namuhla nga] LT', + nextDay: '[Kusasa nga] LT', + nextWeek: 'dddd [nga] LT', + lastDay: '[Itolo nga] LT', + lastWeek: 'dddd [leliphelile] [nga] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'nga %s', + past: 'wenteka nga %s', + s: 'emizuzwana lomcane', + ss: '%d mzuzwana', + m: 'umzuzu', + mm: '%d emizuzu', + h: 'lihora', + hh: '%d emahora', + d: 'lilanga', + dd: '%d emalanga', + M: 'inyanga', + MM: '%d tinyanga', + y: 'umnyaka', + yy: '%d iminyaka', + }, + meridiemParse: /ekuseni|emini|entsambama|ebusuku/, + meridiem: function (hours, minutes, isLower) { + if (hours < 11) { + return 'ekuseni'; + } else if (hours < 15) { + return 'emini'; + } else if (hours < 19) { + return 'entsambama'; + } else { + return 'ebusuku'; + } + }, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ekuseni') { + return hour; + } else if (meridiem === 'emini') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { + if (hour === 0) { + return 0; + } + return hour + 12; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal: '%d', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return ss; + +}))); + + +/***/ }), + +/***/ 41011: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Swedish [sv] +//! author : Jens Alm : https://github.com/ulmus + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var sv = moment.defineLocale('sv', { + months: 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split( + '_' + ), + monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), + weekdays: 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), + weekdaysShort: 'sön_mån_tis_ons_tor_fre_lör'.split('_'), + weekdaysMin: 'sö_må_ti_on_to_fr_lö'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [kl.] HH:mm', + LLLL: 'dddd D MMMM YYYY [kl.] HH:mm', + lll: 'D MMM YYYY HH:mm', + llll: 'ddd D MMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Idag] LT', + nextDay: '[Imorgon] LT', + lastDay: '[Igår] LT', + nextWeek: '[På] dddd LT', + lastWeek: '[I] dddd[s] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'om %s', + past: 'för %s sedan', + s: 'några sekunder', + ss: '%d sekunder', + m: 'en minut', + mm: '%d minuter', + h: 'en timme', + hh: '%d timmar', + d: 'en dag', + dd: '%d dagar', + M: 'en månad', + MM: '%d månader', + y: 'ett år', + yy: '%d år', + }, + dayOfMonthOrdinalParse: /\d{1,2}(\:e|\:a)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? ':e' + : b === 1 + ? ':a' + : b === 2 + ? ':a' + : b === 3 + ? ':e' + : ':e'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return sv; + +}))); + + +/***/ }), + +/***/ 40748: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Swahili [sw] +//! author : Fahad Kassim : https://github.com/fadsel + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var sw = moment.defineLocale('sw', { + months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split( + '_' + ), + monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), + weekdays: + 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split( + '_' + ), + weekdaysShort: 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), + weekdaysMin: 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'hh:mm A', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[leo saa] LT', + nextDay: '[kesho saa] LT', + nextWeek: '[wiki ijayo] dddd [saat] LT', + lastDay: '[jana] LT', + lastWeek: '[wiki iliyopita] dddd [saat] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s baadaye', + past: 'tokea %s', + s: 'hivi punde', + ss: 'sekunde %d', + m: 'dakika moja', + mm: 'dakika %d', + h: 'saa limoja', + hh: 'masaa %d', + d: 'siku moja', + dd: 'siku %d', + M: 'mwezi mmoja', + MM: 'miezi %d', + y: 'mwaka mmoja', + yy: 'miaka %d', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return sw; + +}))); + + +/***/ }), + +/***/ 11025: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Tamil [ta] +//! author : Arjunkumar Krishnamoorthy : https://github.com/tk120404 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var symbolMap = { + 1: '௧', + 2: '௨', + 3: '௩', + 4: '௪', + 5: '௫', + 6: '௬', + 7: '௭', + 8: '௮', + 9: '௯', + 0: '௦', + }, + numberMap = { + '௧': '1', + '௨': '2', + '௩': '3', + '௪': '4', + '௫': '5', + '௬': '6', + '௭': '7', + '௮': '8', + '௯': '9', + '௦': '0', + }; + + var ta = moment.defineLocale('ta', { + months: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split( + '_' + ), + monthsShort: + 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split( + '_' + ), + weekdays: + 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split( + '_' + ), + weekdaysShort: 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split( + '_' + ), + weekdaysMin: 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, HH:mm', + LLLL: 'dddd, D MMMM YYYY, HH:mm', + }, + calendar: { + sameDay: '[இன்று] LT', + nextDay: '[நாளை] LT', + nextWeek: 'dddd, LT', + lastDay: '[நேற்று] LT', + lastWeek: '[கடந்த வாரம்] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s இல்', + past: '%s முன்', + s: 'ஒரு சில விநாடிகள்', + ss: '%d விநாடிகள்', + m: 'ஒரு நிமிடம்', + mm: '%d நிமிடங்கள்', + h: 'ஒரு மணி நேரம்', + hh: '%d மணி நேரம்', + d: 'ஒரு நாள்', + dd: '%d நாட்கள்', + M: 'ஒரு மாதம்', + MM: '%d மாதங்கள்', + y: 'ஒரு வருடம்', + yy: '%d ஆண்டுகள்', + }, + dayOfMonthOrdinalParse: /\d{1,2}வது/, + ordinal: function (number) { + return number + 'வது'; + }, + preparse: function (string) { + return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // refer http://ta.wikipedia.org/s/1er1 + meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, + meridiem: function (hour, minute, isLower) { + if (hour < 2) { + return ' யாமம்'; + } else if (hour < 6) { + return ' வைகறை'; // வைகறை + } else if (hour < 10) { + return ' காலை'; // காலை + } else if (hour < 14) { + return ' நண்பகல்'; // நண்பகல் + } else if (hour < 18) { + return ' எற்பாடு'; // எற்பாடு + } else if (hour < 22) { + return ' மாலை'; // மாலை + } else { + return ' யாமம்'; + } + }, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'யாமம்') { + return hour < 2 ? hour : hour + 12; + } else if (meridiem === 'வைகறை' || meridiem === 'காலை') { + return hour; + } else if (meridiem === 'நண்பகல்') { + return hour >= 10 ? hour : hour + 12; + } else { + return hour + 12; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return ta; + +}))); + + +/***/ }), + +/***/ 11885: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Telugu [te] +//! author : Krishna Chaitanya Thota : https://github.com/kcthota + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var te = moment.defineLocale('te', { + months: 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జులై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split( + '_' + ), + monthsShort: + 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జులై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split( + '_' + ), + weekdaysShort: 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), + weekdaysMin: 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), + longDateFormat: { + LT: 'A h:mm', + LTS: 'A h:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm', + LLLL: 'dddd, D MMMM YYYY, A h:mm', + }, + calendar: { + sameDay: '[నేడు] LT', + nextDay: '[రేపు] LT', + nextWeek: 'dddd, LT', + lastDay: '[నిన్న] LT', + lastWeek: '[గత] dddd, LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s లో', + past: '%s క్రితం', + s: 'కొన్ని క్షణాలు', + ss: '%d సెకన్లు', + m: 'ఒక నిమిషం', + mm: '%d నిమిషాలు', + h: 'ఒక గంట', + hh: '%d గంటలు', + d: 'ఒక రోజు', + dd: '%d రోజులు', + M: 'ఒక నెల', + MM: '%d నెలలు', + y: 'ఒక సంవత్సరం', + yy: '%d సంవత్సరాలు', + }, + dayOfMonthOrdinalParse: /\d{1,2}వ/, + ordinal: '%dవ', + meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'రాత్రి') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ఉదయం') { + return hour; + } else if (meridiem === 'మధ్యాహ్నం') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'సాయంత్రం') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'రాత్రి'; + } else if (hour < 10) { + return 'ఉదయం'; + } else if (hour < 17) { + return 'మధ్యాహ్నం'; + } else if (hour < 20) { + return 'సాయంత్రం'; + } else { + return 'రాత్రి'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }, + }); + + return te; + +}))); + + +/***/ }), + +/***/ 28861: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Tetun Dili (East Timor) [tet] +//! author : Joshua Brooks : https://github.com/joshbrooks +//! author : Onorio De J. Afonso : https://github.com/marobo +//! author : Sonia Simoes : https://github.com/soniasimoes + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var tet = moment.defineLocale('tet', { + months: 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split( + '_' + ), + monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), + weekdays: 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'), + weekdaysShort: 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'), + weekdaysMin: 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Ohin iha] LT', + nextDay: '[Aban iha] LT', + nextWeek: 'dddd [iha] LT', + lastDay: '[Horiseik iha] LT', + lastWeek: 'dddd [semana kotuk] [iha] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'iha %s', + past: '%s liuba', + s: 'segundu balun', + ss: 'segundu %d', + m: 'minutu ida', + mm: 'minutu %d', + h: 'oras ida', + hh: 'oras %d', + d: 'loron ida', + dd: 'loron %d', + M: 'fulan ida', + MM: 'fulan %d', + y: 'tinan ida', + yy: 'tinan %d', + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return tet; + +}))); + + +/***/ }), + +/***/ 86571: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Tajik [tg] +//! author : Orif N. Jr. : https://github.com/orif-jr + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 0: '-ум', + 1: '-ум', + 2: '-юм', + 3: '-юм', + 4: '-ум', + 5: '-ум', + 6: '-ум', + 7: '-ум', + 8: '-ум', + 9: '-ум', + 10: '-ум', + 12: '-ум', + 13: '-ум', + 20: '-ум', + 30: '-юм', + 40: '-ум', + 50: '-ум', + 60: '-ум', + 70: '-ум', + 80: '-ум', + 90: '-ум', + 100: '-ум', + }; + + var tg = moment.defineLocale('tg', { + months: { + format: 'январи_феврали_марти_апрели_майи_июни_июли_августи_сентябри_октябри_ноябри_декабри'.split( + '_' + ), + standalone: + 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split( + '_' + ), + }, + monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), + weekdays: 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split( + '_' + ), + weekdaysShort: 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'), + weekdaysMin: 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Имрӯз соати] LT', + nextDay: '[Фардо соати] LT', + lastDay: '[Дирӯз соати] LT', + nextWeek: 'dddd[и] [ҳафтаи оянда соати] LT', + lastWeek: 'dddd[и] [ҳафтаи гузашта соати] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'баъди %s', + past: '%s пеш', + s: 'якчанд сония', + m: 'як дақиқа', + mm: '%d дақиқа', + h: 'як соат', + hh: '%d соат', + d: 'як рӯз', + dd: '%d рӯз', + M: 'як моҳ', + MM: '%d моҳ', + y: 'як сол', + yy: '%d сол', + }, + meridiemParse: /шаб|субҳ|рӯз|бегоҳ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'шаб') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'субҳ') { + return hour; + } else if (meridiem === 'рӯз') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'бегоҳ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'шаб'; + } else if (hour < 11) { + return 'субҳ'; + } else if (hour < 16) { + return 'рӯз'; + } else if (hour < 19) { + return 'бегоҳ'; + } else { + return 'шаб'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/, + ordinal: function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 1th is the first week of the year. + }, + }); + + return tg; + +}))); + + +/***/ }), + +/***/ 55802: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Thai [th] +//! author : Kridsada Thanabulpong : https://github.com/sirn + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var th = moment.defineLocale('th', { + months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split( + '_' + ), + monthsShort: + 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), + weekdaysShort: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference + weekdaysMin: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'H:mm', + LTS: 'H:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY เวลา H:mm', + LLLL: 'วันddddที่ D MMMM YYYY เวลา H:mm', + }, + meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, + isPM: function (input) { + return input === 'หลังเที่ยง'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ก่อนเที่ยง'; + } else { + return 'หลังเที่ยง'; + } + }, + calendar: { + sameDay: '[วันนี้ เวลา] LT', + nextDay: '[พรุ่งนี้ เวลา] LT', + nextWeek: 'dddd[หน้า เวลา] LT', + lastDay: '[เมื่อวานนี้ เวลา] LT', + lastWeek: '[วัน]dddd[ที่แล้ว เวลา] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'อีก %s', + past: '%sที่แล้ว', + s: 'ไม่กี่วินาที', + ss: '%d วินาที', + m: '1 นาที', + mm: '%d นาที', + h: '1 ชั่วโมง', + hh: '%d ชั่วโมง', + d: '1 วัน', + dd: '%d วัน', + w: '1 สัปดาห์', + ww: '%d สัปดาห์', + M: '1 เดือน', + MM: '%d เดือน', + y: '1 ปี', + yy: '%d ปี', + }, + }); + + return th; + +}))); + + +/***/ }), + +/***/ 59527: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Turkmen [tk] +//! author : Atamyrat Abdyrahmanov : https://github.com/atamyratabdy + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 1: "'inji", + 5: "'inji", + 8: "'inji", + 70: "'inji", + 80: "'inji", + 2: "'nji", + 7: "'nji", + 20: "'nji", + 50: "'nji", + 3: "'ünji", + 4: "'ünji", + 100: "'ünji", + 6: "'njy", + 9: "'unjy", + 10: "'unjy", + 30: "'unjy", + 60: "'ynjy", + 90: "'ynjy", + }; + + var tk = moment.defineLocale('tk', { + months: 'Ýanwar_Fewral_Mart_Aprel_Maý_Iýun_Iýul_Awgust_Sentýabr_Oktýabr_Noýabr_Dekabr'.split( + '_' + ), + monthsShort: 'Ýan_Few_Mar_Apr_Maý_Iýn_Iýl_Awg_Sen_Okt_Noý_Dek'.split('_'), + weekdays: 'Ýekşenbe_Duşenbe_Sişenbe_Çarşenbe_Penşenbe_Anna_Şenbe'.split( + '_' + ), + weekdaysShort: 'Ýek_Duş_Siş_Çar_Pen_Ann_Şen'.split('_'), + weekdaysMin: 'Ýk_Dş_Sş_Çr_Pn_An_Şn'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[bugün sagat] LT', + nextDay: '[ertir sagat] LT', + nextWeek: '[indiki] dddd [sagat] LT', + lastDay: '[düýn] LT', + lastWeek: '[geçen] dddd [sagat] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s soň', + past: '%s öň', + s: 'birnäçe sekunt', + m: 'bir minut', + mm: '%d minut', + h: 'bir sagat', + hh: '%d sagat', + d: 'bir gün', + dd: '%d gün', + M: 'bir aý', + MM: '%d aý', + y: 'bir ýyl', + yy: '%d ýyl', + }, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'Do': + case 'DD': + return number; + default: + if (number === 0) { + // special case for zero + return number + "'unjy"; + } + var a = number % 10, + b = (number % 100) - a, + c = number >= 100 ? 100 : null; + return number + (suffixes[a] || suffixes[b] || suffixes[c]); + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return tk; + +}))); + + +/***/ }), + +/***/ 29231: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Tagalog (Philippines) [tl-ph] +//! author : Dan Hagman : https://github.com/hagmandan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var tlPh = moment.defineLocale('tl-ph', { + months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split( + '_' + ), + monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), + weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split( + '_' + ), + weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), + weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'MM/D/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY HH:mm', + LLLL: 'dddd, MMMM DD, YYYY HH:mm', + }, + calendar: { + sameDay: 'LT [ngayong araw]', + nextDay: '[Bukas ng] LT', + nextWeek: 'LT [sa susunod na] dddd', + lastDay: 'LT [kahapon]', + lastWeek: 'LT [noong nakaraang] dddd', + sameElse: 'L', + }, + relativeTime: { + future: 'sa loob ng %s', + past: '%s ang nakalipas', + s: 'ilang segundo', + ss: '%d segundo', + m: 'isang minuto', + mm: '%d minuto', + h: 'isang oras', + hh: '%d oras', + d: 'isang araw', + dd: '%d araw', + M: 'isang buwan', + MM: '%d buwan', + y: 'isang taon', + yy: '%d taon', + }, + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal: function (number) { + return number; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return tlPh; + +}))); + + +/***/ }), + +/***/ 31052: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Klingon [tlh] +//! author : Dominika Kruk : https://github.com/amaranthrose + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); + + function translateFuture(output) { + var time = output; + time = + output.indexOf('jaj') !== -1 + ? time.slice(0, -3) + 'leS' + : output.indexOf('jar') !== -1 + ? time.slice(0, -3) + 'waQ' + : output.indexOf('DIS') !== -1 + ? time.slice(0, -3) + 'nem' + : time + ' pIq'; + return time; + } + + function translatePast(output) { + var time = output; + time = + output.indexOf('jaj') !== -1 + ? time.slice(0, -3) + 'Hu’' + : output.indexOf('jar') !== -1 + ? time.slice(0, -3) + 'wen' + : output.indexOf('DIS') !== -1 + ? time.slice(0, -3) + 'ben' + : time + ' ret'; + return time; + } + + function translate(number, withoutSuffix, string, isFuture) { + var numberNoun = numberAsNoun(number); + switch (string) { + case 'ss': + return numberNoun + ' lup'; + case 'mm': + return numberNoun + ' tup'; + case 'hh': + return numberNoun + ' rep'; + case 'dd': + return numberNoun + ' jaj'; + case 'MM': + return numberNoun + ' jar'; + case 'yy': + return numberNoun + ' DIS'; + } + } + + function numberAsNoun(number) { + var hundred = Math.floor((number % 1000) / 100), + ten = Math.floor((number % 100) / 10), + one = number % 10, + word = ''; + if (hundred > 0) { + word += numbersNouns[hundred] + 'vatlh'; + } + if (ten > 0) { + word += (word !== '' ? ' ' : '') + numbersNouns[ten] + 'maH'; + } + if (one > 0) { + word += (word !== '' ? ' ' : '') + numbersNouns[one]; + } + return word === '' ? 'pagh' : word; + } + + var tlh = moment.defineLocale('tlh', { + months: 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split( + '_' + ), + monthsShort: + 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split( + '_' + ), + weekdaysShort: + 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), + weekdaysMin: + 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[DaHjaj] LT', + nextDay: '[wa’leS] LT', + nextWeek: 'LLL', + lastDay: '[wa’Hu’] LT', + lastWeek: 'LLL', + sameElse: 'L', + }, + relativeTime: { + future: translateFuture, + past: translatePast, + s: 'puS lup', + ss: translate, + m: 'wa’ tup', + mm: translate, + h: 'wa’ rep', + hh: translate, + d: 'wa’ jaj', + dd: translate, + M: 'wa’ jar', + MM: translate, + y: 'wa’ DIS', + yy: translate, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return tlh; + +}))); + + +/***/ }), + +/***/ 85096: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Turkish [tr] +//! authors : Erhan Gundogan : https://github.com/erhangundogan, +//! Burak Yiğit Kaya: https://github.com/BYK + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var suffixes = { + 1: "'inci", + 5: "'inci", + 8: "'inci", + 70: "'inci", + 80: "'inci", + 2: "'nci", + 7: "'nci", + 20: "'nci", + 50: "'nci", + 3: "'üncü", + 4: "'üncü", + 100: "'üncü", + 6: "'ncı", + 9: "'uncu", + 10: "'uncu", + 30: "'uncu", + 60: "'ıncı", + 90: "'ıncı", + }; + + var tr = moment.defineLocale('tr', { + months: 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split( + '_' + ), + monthsShort: 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), + weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split( + '_' + ), + weekdaysShort: 'Paz_Pzt_Sal_Çar_Per_Cum_Cmt'.split('_'), + weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), + meridiem: function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'öö' : 'ÖÖ'; + } else { + return isLower ? 'ös' : 'ÖS'; + } + }, + meridiemParse: /öö|ÖÖ|ös|ÖS/, + isPM: function (input) { + return input === 'ös' || input === 'ÖS'; + }, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[bugün saat] LT', + nextDay: '[yarın saat] LT', + nextWeek: '[gelecek] dddd [saat] LT', + lastDay: '[dün] LT', + lastWeek: '[geçen] dddd [saat] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s sonra', + past: '%s önce', + s: 'birkaç saniye', + ss: '%d saniye', + m: 'bir dakika', + mm: '%d dakika', + h: 'bir saat', + hh: '%d saat', + d: 'bir gün', + dd: '%d gün', + w: 'bir hafta', + ww: '%d hafta', + M: 'bir ay', + MM: '%d ay', + y: 'bir yıl', + yy: '%d yıl', + }, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'Do': + case 'DD': + return number; + default: + if (number === 0) { + // special case for zero + return number + "'ıncı"; + } + var a = number % 10, + b = (number % 100) - a, + c = number >= 100 ? 100 : null; + return number + (suffixes[a] || suffixes[b] || suffixes[c]); + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return tr; + +}))); + + +/***/ }), + +/***/ 79846: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Talossan [tzl] +//! author : Robin van der Vliet : https://github.com/robin0van0der0v +//! author : Iustì Canun + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals. + // This is currently too difficult (maybe even impossible) to add. + var tzl = moment.defineLocale('tzl', { + months: 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split( + '_' + ), + monthsShort: 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), + weekdays: 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), + weekdaysShort: 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), + weekdaysMin: 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), + longDateFormat: { + LT: 'HH.mm', + LTS: 'HH.mm.ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM [dallas] YYYY', + LLL: 'D. MMMM [dallas] YYYY HH.mm', + LLLL: 'dddd, [li] D. MMMM [dallas] YYYY HH.mm', + }, + meridiemParse: /d\'o|d\'a/i, + isPM: function (input) { + return "d'o" === input.toLowerCase(); + }, + meridiem: function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? "d'o" : "D'O"; + } else { + return isLower ? "d'a" : "D'A"; + } + }, + calendar: { + sameDay: '[oxhi à] LT', + nextDay: '[demà à] LT', + nextWeek: 'dddd [à] LT', + lastDay: '[ieiri à] LT', + lastWeek: '[sür el] dddd [lasteu à] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'osprei %s', + past: 'ja%s', + s: processRelativeTime, + ss: processRelativeTime, + m: processRelativeTime, + mm: processRelativeTime, + h: processRelativeTime, + hh: processRelativeTime, + d: processRelativeTime, + dd: processRelativeTime, + M: processRelativeTime, + MM: processRelativeTime, + y: processRelativeTime, + yy: processRelativeTime, + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + s: ['viensas secunds', "'iensas secunds"], + ss: [number + ' secunds', '' + number + ' secunds'], + m: ["'n míut", "'iens míut"], + mm: [number + ' míuts', '' + number + ' míuts'], + h: ["'n þora", "'iensa þora"], + hh: [number + ' þoras', '' + number + ' þoras'], + d: ["'n ziua", "'iensa ziua"], + dd: [number + ' ziuas', '' + number + ' ziuas'], + M: ["'n mes", "'iens mes"], + MM: [number + ' mesen', '' + number + ' mesen'], + y: ["'n ar", "'iens ar"], + yy: [number + ' ars', '' + number + ' ars'], + }; + return isFuture + ? format[key][0] + : withoutSuffix + ? format[key][0] + : format[key][1]; + } + + return tzl; + +}))); + + +/***/ }), + +/***/ 97711: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Central Atlas Tamazight Latin [tzm-latn] +//! author : Abdel Said : https://github.com/abdelsaid + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var tzmLatn = moment.defineLocale('tzm-latn', { + months: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split( + '_' + ), + monthsShort: + 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split( + '_' + ), + weekdays: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), + weekdaysShort: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), + weekdaysMin: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[asdkh g] LT', + nextDay: '[aska g] LT', + nextWeek: 'dddd [g] LT', + lastDay: '[assant g] LT', + lastWeek: 'dddd [g] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'dadkh s yan %s', + past: 'yan %s', + s: 'imik', + ss: '%d imik', + m: 'minuḍ', + mm: '%d minuḍ', + h: 'saɛa', + hh: '%d tassaɛin', + d: 'ass', + dd: '%d ossan', + M: 'ayowr', + MM: '%d iyyirn', + y: 'asgas', + yy: '%d isgasn', + }, + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return tzmLatn; + +}))); + + +/***/ }), + +/***/ 81765: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Central Atlas Tamazight [tzm] +//! author : Abdel Said : https://github.com/abdelsaid + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var tzm = moment.defineLocale('tzm', { + months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split( + '_' + ), + monthsShort: + 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split( + '_' + ), + weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), + weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), + weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', + nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', + nextWeek: 'dddd [ⴴ] LT', + lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', + lastWeek: 'dddd [ⴴ] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', + past: 'ⵢⴰⵏ %s', + s: 'ⵉⵎⵉⴽ', + ss: '%d ⵉⵎⵉⴽ', + m: 'ⵎⵉⵏⵓⴺ', + mm: '%d ⵎⵉⵏⵓⴺ', + h: 'ⵙⴰⵄⴰ', + hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', + d: 'ⴰⵙⵙ', + dd: '%d oⵙⵙⴰⵏ', + M: 'ⴰⵢoⵓⵔ', + MM: '%d ⵉⵢⵢⵉⵔⵏ', + y: 'ⴰⵙⴳⴰⵙ', + yy: '%d ⵉⵙⴳⴰⵙⵏ', + }, + week: { + dow: 6, // Saturday is the first day of the week. + doy: 12, // The week that contains Jan 12th is the first week of the year. + }, + }); + + return tzm; + +}))); + + +/***/ }), + +/***/ 48414: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Uyghur (China) [ug-cn] +//! author: boyaq : https://github.com/boyaq + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var ugCn = moment.defineLocale('ug-cn', { + months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( + '_' + ), + monthsShort: + 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( + '_' + ), + weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split( + '_' + ), + weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), + weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى', + LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', + LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', + }, + meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ( + meridiem === 'يېرىم كېچە' || + meridiem === 'سەھەر' || + meridiem === 'چۈشتىن بۇرۇن' + ) { + return hour; + } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') { + return hour + 12; + } else { + return hour >= 11 ? hour : hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return 'يېرىم كېچە'; + } else if (hm < 900) { + return 'سەھەر'; + } else if (hm < 1130) { + return 'چۈشتىن بۇرۇن'; + } else if (hm < 1230) { + return 'چۈش'; + } else if (hm < 1800) { + return 'چۈشتىن كېيىن'; + } else { + return 'كەچ'; + } + }, + calendar: { + sameDay: '[بۈگۈن سائەت] LT', + nextDay: '[ئەتە سائەت] LT', + nextWeek: '[كېلەركى] dddd [سائەت] LT', + lastDay: '[تۆنۈگۈن] LT', + lastWeek: '[ئالدىنقى] dddd [سائەت] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s كېيىن', + past: '%s بۇرۇن', + s: 'نەچچە سېكونت', + ss: '%d سېكونت', + m: 'بىر مىنۇت', + mm: '%d مىنۇت', + h: 'بىر سائەت', + hh: '%d سائەت', + d: 'بىر كۈن', + dd: '%d كۈن', + M: 'بىر ئاي', + MM: '%d ئاي', + y: 'بىر يىل', + yy: '%d يىل', + }, + + dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '-كۈنى'; + case 'w': + case 'W': + return number + '-ھەپتە'; + default: + return number; + } + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 1st is the first week of the year. + }, + }); + + return ugCn; + +}))); + + +/***/ }), + +/***/ 16618: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Ukrainian [uk] +//! author : zemlanin : https://github.com/zemlanin +//! Author : Menelion Elensúle : https://github.com/Oire + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 + ? forms[0] + : num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) + ? forms[1] + : forms[2]; + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + ss: withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд', + mm: withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', + hh: withoutSuffix ? 'година_години_годин' : 'годину_години_годин', + dd: 'день_дні_днів', + MM: 'місяць_місяці_місяців', + yy: 'рік_роки_років', + }; + if (key === 'm') { + return withoutSuffix ? 'хвилина' : 'хвилину'; + } else if (key === 'h') { + return withoutSuffix ? 'година' : 'годину'; + } else { + return number + ' ' + plural(format[key], +number); + } + } + function weekdaysCaseReplace(m, format) { + var weekdays = { + nominative: + 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split( + '_' + ), + accusative: + 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split( + '_' + ), + genitive: + 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split( + '_' + ), + }, + nounCase; + + if (m === true) { + return weekdays['nominative'] + .slice(1, 7) + .concat(weekdays['nominative'].slice(0, 1)); + } + if (!m) { + return weekdays['nominative']; + } + + nounCase = /(\[[ВвУу]\]) ?dddd/.test(format) + ? 'accusative' + : /\[?(?:минулої|наступної)? ?\] ?dddd/.test(format) + ? 'genitive' + : 'nominative'; + return weekdays[nounCase][m.day()]; + } + function processHoursFunction(str) { + return function () { + return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; + }; + } + + var uk = moment.defineLocale('uk', { + months: { + format: 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split( + '_' + ), + standalone: + 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split( + '_' + ), + }, + monthsShort: 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split( + '_' + ), + weekdays: weekdaysCaseReplace, + weekdaysShort: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), + weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D MMMM YYYY р.', + LLL: 'D MMMM YYYY р., HH:mm', + LLLL: 'dddd, D MMMM YYYY р., HH:mm', + }, + calendar: { + sameDay: processHoursFunction('[Сьогодні '), + nextDay: processHoursFunction('[Завтра '), + lastDay: processHoursFunction('[Вчора '), + nextWeek: processHoursFunction('[У] dddd ['), + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 5: + case 6: + return processHoursFunction('[Минулої] dddd [').call(this); + case 1: + case 2: + case 4: + return processHoursFunction('[Минулого] dddd [').call(this); + } + }, + sameElse: 'L', + }, + relativeTime: { + future: 'за %s', + past: '%s тому', + s: 'декілька секунд', + ss: relativeTimeWithPlural, + m: relativeTimeWithPlural, + mm: relativeTimeWithPlural, + h: 'годину', + hh: relativeTimeWithPlural, + d: 'день', + dd: relativeTimeWithPlural, + M: 'місяць', + MM: relativeTimeWithPlural, + y: 'рік', + yy: relativeTimeWithPlural, + }, + // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason + meridiemParse: /ночі|ранку|дня|вечора/, + isPM: function (input) { + return /^(дня|вечора)$/.test(input); + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'ночі'; + } else if (hour < 12) { + return 'ранку'; + } else if (hour < 17) { + return 'дня'; + } else { + return 'вечора'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return number + '-й'; + case 'D': + return number + '-го'; + default: + return number; + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return uk; + +}))); + + +/***/ }), + +/***/ 57777: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Urdu [ur] +//! author : Sawood Alam : https://github.com/ibnesayeed +//! author : Zack : https://github.com/ZackVision + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var months = [ + 'جنوری', + 'فروری', + 'مارچ', + 'اپریل', + 'مئی', + 'جون', + 'جولائی', + 'اگست', + 'ستمبر', + 'اکتوبر', + 'نومبر', + 'دسمبر', + ], + days = ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ']; + + var ur = moment.defineLocale('ur', { + months: months, + monthsShort: months, + weekdays: days, + weekdaysShort: days, + weekdaysMin: days, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd، D MMMM YYYY HH:mm', + }, + meridiemParse: /صبح|شام/, + isPM: function (input) { + return 'شام' === input; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'صبح'; + } + return 'شام'; + }, + calendar: { + sameDay: '[آج بوقت] LT', + nextDay: '[کل بوقت] LT', + nextWeek: 'dddd [بوقت] LT', + lastDay: '[گذشتہ روز بوقت] LT', + lastWeek: '[گذشتہ] dddd [بوقت] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s بعد', + past: '%s قبل', + s: 'چند سیکنڈ', + ss: '%d سیکنڈ', + m: 'ایک منٹ', + mm: '%d منٹ', + h: 'ایک گھنٹہ', + hh: '%d گھنٹے', + d: 'ایک دن', + dd: '%d دن', + M: 'ایک ماہ', + MM: '%d ماہ', + y: 'ایک سال', + yy: '%d سال', + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return ur; + +}))); + + +/***/ }), + +/***/ 72475: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Uzbek Latin [uz-latn] +//! author : Rasulbek Mirzayev : github.com/Rasulbeeek + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var uzLatn = moment.defineLocale('uz-latn', { + months: 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split( + '_' + ), + monthsShort: 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'), + weekdays: + 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split( + '_' + ), + weekdaysShort: 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'), + weekdaysMin: 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'D MMMM YYYY, dddd HH:mm', + }, + calendar: { + sameDay: '[Bugun soat] LT [da]', + nextDay: '[Ertaga] LT [da]', + nextWeek: 'dddd [kuni soat] LT [da]', + lastDay: '[Kecha soat] LT [da]', + lastWeek: "[O'tgan] dddd [kuni soat] LT [da]", + sameElse: 'L', + }, + relativeTime: { + future: 'Yaqin %s ichida', + past: 'Bir necha %s oldin', + s: 'soniya', + ss: '%d soniya', + m: 'bir daqiqa', + mm: '%d daqiqa', + h: 'bir soat', + hh: '%d soat', + d: 'bir kun', + dd: '%d kun', + M: 'bir oy', + MM: '%d oy', + y: 'bir yil', + yy: '%d yil', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 7th is the first week of the year. + }, + }); + + return uzLatn; + +}))); + + +/***/ }), + +/***/ 57609: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Uzbek [uz] +//! author : Sardor Muminov : https://github.com/muminoff + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var uz = moment.defineLocale('uz', { + months: 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split( + '_' + ), + monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), + weekdays: 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), + weekdaysShort: 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), + weekdaysMin: 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'D MMMM YYYY, dddd HH:mm', + }, + calendar: { + sameDay: '[Бугун соат] LT [да]', + nextDay: '[Эртага] LT [да]', + nextWeek: 'dddd [куни соат] LT [да]', + lastDay: '[Кеча соат] LT [да]', + lastWeek: '[Утган] dddd [куни соат] LT [да]', + sameElse: 'L', + }, + relativeTime: { + future: 'Якин %s ичида', + past: 'Бир неча %s олдин', + s: 'фурсат', + ss: '%d фурсат', + m: 'бир дакика', + mm: '%d дакика', + h: 'бир соат', + hh: '%d соат', + d: 'бир кун', + dd: '%d кун', + M: 'бир ой', + MM: '%d ой', + y: 'бир йил', + yy: '%d йил', + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 7, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return uz; + +}))); + + +/***/ }), + +/***/ 21135: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Vietnamese [vi] +//! author : Bang Nguyen : https://github.com/bangnk +//! author : Chien Kira : https://github.com/chienkira + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var vi = moment.defineLocale('vi', { + months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split( + '_' + ), + monthsShort: + 'Thg 01_Thg 02_Thg 03_Thg 04_Thg 05_Thg 06_Thg 07_Thg 08_Thg 09_Thg 10_Thg 11_Thg 12'.split( + '_' + ), + monthsParseExact: true, + weekdays: 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split( + '_' + ), + weekdaysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), + weekdaysMin: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), + weekdaysParseExact: true, + meridiemParse: /sa|ch/i, + isPM: function (input) { + return /^ch$/i.test(input); + }, + meridiem: function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'sa' : 'SA'; + } else { + return isLower ? 'ch' : 'CH'; + } + }, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM [năm] YYYY', + LLL: 'D MMMM [năm] YYYY HH:mm', + LLLL: 'dddd, D MMMM [năm] YYYY HH:mm', + l: 'DD/M/YYYY', + ll: 'D MMM YYYY', + lll: 'D MMM YYYY HH:mm', + llll: 'ddd, D MMM YYYY HH:mm', + }, + calendar: { + sameDay: '[Hôm nay lúc] LT', + nextDay: '[Ngày mai lúc] LT', + nextWeek: 'dddd [tuần tới lúc] LT', + lastDay: '[Hôm qua lúc] LT', + lastWeek: 'dddd [tuần trước lúc] LT', + sameElse: 'L', + }, + relativeTime: { + future: '%s tới', + past: '%s trước', + s: 'vài giây', + ss: '%d giây', + m: 'một phút', + mm: '%d phút', + h: 'một giờ', + hh: '%d giờ', + d: 'một ngày', + dd: '%d ngày', + w: 'một tuần', + ww: '%d tuần', + M: 'một tháng', + MM: '%d tháng', + y: 'một năm', + yy: '%d năm', + }, + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal: function (number) { + return number; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return vi; + +}))); + + +/***/ }), + +/***/ 64051: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Pseudo [x-pseudo] +//! author : Andrew Hood : https://github.com/andrewhood125 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var xPseudo = moment.defineLocale('x-pseudo', { + months: 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split( + '_' + ), + monthsShort: + 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split( + '_' + ), + monthsParseExact: true, + weekdays: + 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split( + '_' + ), + weekdaysShort: 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), + weekdaysMin: 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm', + }, + calendar: { + sameDay: '[T~ódá~ý át] LT', + nextDay: '[T~ómó~rró~w át] LT', + nextWeek: 'dddd [át] LT', + lastDay: '[Ý~ést~érdá~ý át] LT', + lastWeek: '[L~ást] dddd [át] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'í~ñ %s', + past: '%s á~gó', + s: 'á ~féw ~sécó~ñds', + ss: '%d s~écóñ~ds', + m: 'á ~míñ~úté', + mm: '%d m~íñú~tés', + h: 'á~ñ hó~úr', + hh: '%d h~óúrs', + d: 'á ~dáý', + dd: '%d d~áýs', + M: 'á ~móñ~th', + MM: '%d m~óñt~hs', + y: 'á ~ýéár', + yy: '%d ý~éárs', + }, + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function (number) { + var b = number % 10, + output = + ~~((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return xPseudo; + +}))); + + +/***/ }), + +/***/ 82218: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Yoruba Nigeria [yo] +//! author : Atolagbe Abisoye : https://github.com/andela-batolagbe + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var yo = moment.defineLocale('yo', { + months: 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split( + '_' + ), + monthsShort: 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'), + weekdays: 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'), + weekdaysShort: 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'), + weekdaysMin: 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'), + longDateFormat: { + LT: 'h:mm A', + LTS: 'h:mm:ss A', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY h:mm A', + LLLL: 'dddd, D MMMM YYYY h:mm A', + }, + calendar: { + sameDay: '[Ònì ni] LT', + nextDay: '[Ọ̀la ni] LT', + nextWeek: "dddd [Ọsẹ̀ tón'bọ] [ni] LT", + lastDay: '[Àna ni] LT', + lastWeek: 'dddd [Ọsẹ̀ tólọ́] [ni] LT', + sameElse: 'L', + }, + relativeTime: { + future: 'ní %s', + past: '%s kọjá', + s: 'ìsẹjú aayá die', + ss: 'aayá %d', + m: 'ìsẹjú kan', + mm: 'ìsẹjú %d', + h: 'wákati kan', + hh: 'wákati %d', + d: 'ọjọ́ kan', + dd: 'ọjọ́ %d', + M: 'osù kan', + MM: 'osù %d', + y: 'ọdún kan', + yy: 'ọdún %d', + }, + dayOfMonthOrdinalParse: /ọjọ́\s\d{1,2}/, + ordinal: 'ọjọ́ %d', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return yo; + +}))); + + +/***/ }), + +/***/ 52648: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Chinese (China) [zh-cn] +//! author : suupic : https://github.com/suupic +//! author : Zeno Zeng : https://github.com/zenozeng +//! author : uu109 : https://github.com/uu109 + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var zhCn = moment.defineLocale('zh-cn', { + months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split( + '_' + ), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split( + '_' + ), + weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'), + weekdaysMin: '日_一_二_三_四_五_六'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日Ah点mm分', + LLLL: 'YYYY年M月D日ddddAh点mm分', + l: 'YYYY/M/D', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日dddd HH:mm', + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } else { + // '中午' + return hour >= 11 ? hour : hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; + } + }, + calendar: { + sameDay: '[今天]LT', + nextDay: '[明天]LT', + nextWeek: function (now) { + if (now.week() !== this.week()) { + return '[下]dddLT'; + } else { + return '[本]dddLT'; + } + }, + lastDay: '[昨天]LT', + lastWeek: function (now) { + if (this.week() !== now.week()) { + return '[上]dddLT'; + } else { + return '[本]dddLT'; + } + }, + sameElse: 'L', + }, + dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + case 'M': + return number + '月'; + case 'w': + case 'W': + return number + '周'; + default: + return number; + } + }, + relativeTime: { + future: '%s后', + past: '%s前', + s: '几秒', + ss: '%d 秒', + m: '1 分钟', + mm: '%d 分钟', + h: '1 小时', + hh: '%d 小时', + d: '1 天', + dd: '%d 天', + w: '1 周', + ww: '%d 周', + M: '1 个月', + MM: '%d 个月', + y: '1 年', + yy: '%d 年', + }, + week: { + // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 + dow: 1, // Monday is the first day of the week. + doy: 4, // The week that contains Jan 4th is the first week of the year. + }, + }); + + return zhCn; + +}))); + + +/***/ }), + +/***/ 1632: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Chinese (Hong Kong) [zh-hk] +//! author : Ben : https://github.com/ben-lin +//! author : Chris Lam : https://github.com/hehachris +//! author : Konstantin : https://github.com/skfd +//! author : Anthony : https://github.com/anthonylau + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var zhHk = moment.defineLocale('zh-hk', { + months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split( + '_' + ), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split( + '_' + ), + weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), + weekdaysMin: '日_一_二_三_四_五_六'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日 HH:mm', + LLLL: 'YYYY年M月D日dddd HH:mm', + l: 'YYYY/M/D', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日dddd HH:mm', + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '中午') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1200) { + return '上午'; + } else if (hm === 1200) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; + } + }, + calendar: { + sameDay: '[今天]LT', + nextDay: '[明天]LT', + nextWeek: '[下]ddddLT', + lastDay: '[昨天]LT', + lastWeek: '[上]ddddLT', + sameElse: 'L', + }, + dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + case 'M': + return number + '月'; + case 'w': + case 'W': + return number + '週'; + default: + return number; + } + }, + relativeTime: { + future: '%s後', + past: '%s前', + s: '幾秒', + ss: '%d 秒', + m: '1 分鐘', + mm: '%d 分鐘', + h: '1 小時', + hh: '%d 小時', + d: '1 天', + dd: '%d 天', + M: '1 個月', + MM: '%d 個月', + y: '1 年', + yy: '%d 年', + }, + }); + + return zhHk; + +}))); + + +/***/ }), + +/***/ 31541: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Chinese (Macau) [zh-mo] +//! author : Ben : https://github.com/ben-lin +//! author : Chris Lam : https://github.com/hehachris +//! author : Tan Yuanhong : https://github.com/le0tan + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var zhMo = moment.defineLocale('zh-mo', { + months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split( + '_' + ), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split( + '_' + ), + weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), + weekdaysMin: '日_一_二_三_四_五_六'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日 HH:mm', + LLLL: 'YYYY年M月D日dddd HH:mm', + l: 'D/M/YYYY', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日dddd HH:mm', + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '中午') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; + } + }, + calendar: { + sameDay: '[今天] LT', + nextDay: '[明天] LT', + nextWeek: '[下]dddd LT', + lastDay: '[昨天] LT', + lastWeek: '[上]dddd LT', + sameElse: 'L', + }, + dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + case 'M': + return number + '月'; + case 'w': + case 'W': + return number + '週'; + default: + return number; + } + }, + relativeTime: { + future: '%s內', + past: '%s前', + s: '幾秒', + ss: '%d 秒', + m: '1 分鐘', + mm: '%d 分鐘', + h: '1 小時', + hh: '%d 小時', + d: '1 天', + dd: '%d 天', + M: '1 個月', + MM: '%d 個月', + y: '1 年', + yy: '%d 年', + }, + }); + + return zhMo; + +}))); + + +/***/ }), + +/***/ 50304: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +//! moment.js locale configuration +//! locale : Chinese (Taiwan) [zh-tw] +//! author : Ben : https://github.com/ben-lin +//! author : Chris Lam : https://github.com/hehachris + +;(function (global, factory) { + true ? factory(__webpack_require__(95093)) : + 0 +}(this, (function (moment) { 'use strict'; + + //! moment.js locale configuration + + var zhTw = moment.defineLocale('zh-tw', { + months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split( + '_' + ), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split( + '_' + ), + weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), + weekdaysMin: '日_一_二_三_四_五_六'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日 HH:mm', + LLLL: 'YYYY年M月D日dddd HH:mm', + l: 'YYYY/M/D', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日dddd HH:mm', + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '中午') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; + } + }, + calendar: { + sameDay: '[今天] LT', + nextDay: '[明天] LT', + nextWeek: '[下]dddd LT', + lastDay: '[昨天] LT', + lastWeek: '[上]dddd LT', + sameElse: 'L', + }, + dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + case 'M': + return number + '月'; + case 'w': + case 'W': + return number + '週'; + default: + return number; + } + }, + relativeTime: { + future: '%s後', + past: '%s前', + s: '幾秒', + ss: '%d 秒', + m: '1 分鐘', + mm: '%d 分鐘', + h: '1 小時', + hh: '%d 小時', + d: '1 天', + dd: '%d 天', + M: '1 個月', + MM: '%d 個月', + y: '1 年', + yy: '%d 年', + }, + }); + + return zhTw; + +}))); + + +/***/ }), + +/***/ 35358: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var map = { + "./af": 25177, + "./af.js": 25177, + "./ar": 61509, + "./ar-dz": 41488, + "./ar-dz.js": 41488, + "./ar-kw": 58676, + "./ar-kw.js": 58676, + "./ar-ly": 42353, + "./ar-ly.js": 42353, + "./ar-ma": 24496, + "./ar-ma.js": 24496, + "./ar-ps": 6947, + "./ar-ps.js": 6947, + "./ar-sa": 60301, + "./ar-sa.js": 60301, + "./ar-tn": 89756, + "./ar-tn.js": 89756, + "./ar.js": 61509, + "./az": 95533, + "./az.js": 95533, + "./be": 28959, + "./be.js": 28959, + "./bg": 47777, + "./bg.js": 47777, + "./bm": 54903, + "./bm.js": 54903, + "./bn": 61290, + "./bn-bd": 17357, + "./bn-bd.js": 17357, + "./bn.js": 61290, + "./bo": 31545, + "./bo.js": 31545, + "./br": 11470, + "./br.js": 11470, + "./bs": 44429, + "./bs.js": 44429, + "./ca": 7306, + "./ca.js": 7306, + "./cs": 56464, + "./cs.js": 56464, + "./cv": 73635, + "./cv.js": 73635, + "./cy": 64226, + "./cy.js": 64226, + "./da": 93601, + "./da.js": 93601, + "./de": 77853, + "./de-at": 26111, + "./de-at.js": 26111, + "./de-ch": 54697, + "./de-ch.js": 54697, + "./de.js": 77853, + "./dv": 60708, + "./dv.js": 60708, + "./el": 54691, + "./el.js": 54691, + "./en-au": 53872, + "./en-au.js": 53872, + "./en-ca": 28298, + "./en-ca.js": 28298, + "./en-gb": 56195, + "./en-gb.js": 56195, + "./en-ie": 66584, + "./en-ie.js": 66584, + "./en-il": 65543, + "./en-il.js": 65543, + "./en-in": 9033, + "./en-in.js": 9033, + "./en-nz": 79402, + "./en-nz.js": 79402, + "./en-sg": 43004, + "./en-sg.js": 43004, + "./eo": 32934, + "./eo.js": 32934, + "./es": 97650, + "./es-do": 20838, + "./es-do.js": 20838, + "./es-mx": 17730, + "./es-mx.js": 17730, + "./es-us": 56575, + "./es-us.js": 56575, + "./es.js": 97650, + "./et": 3035, + "./et.js": 3035, + "./eu": 3508, + "./eu.js": 3508, + "./fa": 119, + "./fa.js": 119, + "./fi": 90527, + "./fi.js": 90527, + "./fil": 95995, + "./fil.js": 95995, + "./fo": 52477, + "./fo.js": 52477, + "./fr": 85498, + "./fr-ca": 26435, + "./fr-ca.js": 26435, + "./fr-ch": 37892, + "./fr-ch.js": 37892, + "./fr.js": 85498, + "./fy": 37071, + "./fy.js": 37071, + "./ga": 41734, + "./ga.js": 41734, + "./gd": 70217, + "./gd.js": 70217, + "./gl": 77329, + "./gl.js": 77329, + "./gom-deva": 32124, + "./gom-deva.js": 32124, + "./gom-latn": 93383, + "./gom-latn.js": 93383, + "./gu": 95050, + "./gu.js": 95050, + "./he": 11713, + "./he.js": 11713, + "./hi": 43861, + "./hi.js": 43861, + "./hr": 26308, + "./hr.js": 26308, + "./hu": 90609, + "./hu.js": 90609, + "./hy-am": 17160, + "./hy-am.js": 17160, + "./id": 74063, + "./id.js": 74063, + "./is": 89374, + "./is.js": 89374, + "./it": 88383, + "./it-ch": 21827, + "./it-ch.js": 21827, + "./it.js": 88383, + "./ja": 23827, + "./ja.js": 23827, + "./jv": 89722, + "./jv.js": 89722, + "./ka": 41794, + "./ka.js": 41794, + "./kk": 27088, + "./kk.js": 27088, + "./km": 96870, + "./km.js": 96870, + "./kn": 84451, + "./kn.js": 84451, + "./ko": 63164, + "./ko.js": 63164, + "./ku": 98174, + "./ku-kmr": 6181, + "./ku-kmr.js": 6181, + "./ku.js": 98174, + "./ky": 78474, + "./ky.js": 78474, + "./lb": 79680, + "./lb.js": 79680, + "./lo": 15867, + "./lo.js": 15867, + "./lt": 45766, + "./lt.js": 45766, + "./lv": 69532, + "./lv.js": 69532, + "./me": 58076, + "./me.js": 58076, + "./mi": 41848, + "./mi.js": 41848, + "./mk": 30306, + "./mk.js": 30306, + "./ml": 73739, + "./ml.js": 73739, + "./mn": 99053, + "./mn.js": 99053, + "./mr": 86169, + "./mr.js": 86169, + "./ms": 73386, + "./ms-my": 92297, + "./ms-my.js": 92297, + "./ms.js": 73386, + "./mt": 77075, + "./mt.js": 77075, + "./my": 72264, + "./my.js": 72264, + "./nb": 22274, + "./nb.js": 22274, + "./ne": 8235, + "./ne.js": 8235, + "./nl": 92572, + "./nl-be": 43784, + "./nl-be.js": 43784, + "./nl.js": 92572, + "./nn": 54566, + "./nn.js": 54566, + "./oc-lnc": 69330, + "./oc-lnc.js": 69330, + "./pa-in": 29849, + "./pa-in.js": 29849, + "./pl": 94418, + "./pl.js": 94418, + "./pt": 79834, + "./pt-br": 48303, + "./pt-br.js": 48303, + "./pt.js": 79834, + "./ro": 24457, + "./ro.js": 24457, + "./ru": 82271, + "./ru.js": 82271, + "./sd": 1221, + "./sd.js": 1221, + "./se": 33478, + "./se.js": 33478, + "./si": 17538, + "./si.js": 17538, + "./sk": 5784, + "./sk.js": 5784, + "./sl": 46637, + "./sl.js": 46637, + "./sq": 86794, + "./sq.js": 86794, + "./sr": 45719, + "./sr-cyrl": 3322, + "./sr-cyrl.js": 3322, + "./sr.js": 45719, + "./ss": 56000, + "./ss.js": 56000, + "./sv": 41011, + "./sv.js": 41011, + "./sw": 40748, + "./sw.js": 40748, + "./ta": 11025, + "./ta.js": 11025, + "./te": 11885, + "./te.js": 11885, + "./tet": 28861, + "./tet.js": 28861, + "./tg": 86571, + "./tg.js": 86571, + "./th": 55802, + "./th.js": 55802, + "./tk": 59527, + "./tk.js": 59527, + "./tl-ph": 29231, + "./tl-ph.js": 29231, + "./tlh": 31052, + "./tlh.js": 31052, + "./tr": 85096, + "./tr.js": 85096, + "./tzl": 79846, + "./tzl.js": 79846, + "./tzm": 81765, + "./tzm-latn": 97711, + "./tzm-latn.js": 97711, + "./tzm.js": 81765, + "./ug-cn": 48414, + "./ug-cn.js": 48414, + "./uk": 16618, + "./uk.js": 16618, + "./ur": 57777, + "./ur.js": 57777, + "./uz": 57609, + "./uz-latn": 72475, + "./uz-latn.js": 72475, + "./uz.js": 57609, + "./vi": 21135, + "./vi.js": 21135, + "./x-pseudo": 64051, + "./x-pseudo.js": 64051, + "./yo": 82218, + "./yo.js": 82218, + "./zh-cn": 52648, + "./zh-cn.js": 52648, + "./zh-hk": 1632, + "./zh-hk.js": 1632, + "./zh-mo": 31541, + "./zh-mo.js": 31541, + "./zh-tw": 50304, + "./zh-tw.js": 50304 +}; + + +function webpackContext(req) { + var id = webpackContextResolve(req); + return __webpack_require__(id); +} +function webpackContextResolve(req) { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = 35358; + +/***/ }), + +/***/ 95093: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +/* provided dependency */ var console = __webpack_require__(96763); +//! moment.js +//! version : 2.30.1 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com + +;(function (global, factory) { + true ? module.exports = factory() : + 0 +}(this, (function () { 'use strict'; + + var hookCallback; + + function hooks() { + return hookCallback.apply(null, arguments); + } + + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback(callback) { + hookCallback = callback; + } + + function isArray(input) { + return ( + input instanceof Array || + Object.prototype.toString.call(input) === '[object Array]' + ); + } + + function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return ( + input != null && + Object.prototype.toString.call(input) === '[object Object]' + ); + } + + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } + + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return Object.getOwnPropertyNames(obj).length === 0; + } else { + var k; + for (k in obj) { + if (hasOwnProp(obj, k)) { + return false; + } + } + return true; + } + } + + function isUndefined(input) { + return input === void 0; + } + + function isNumber(input) { + return ( + typeof input === 'number' || + Object.prototype.toString.call(input) === '[object Number]' + ); + } + + function isDate(input) { + return ( + input instanceof Date || + Object.prototype.toString.call(input) === '[object Date]' + ); + } + + function map(arr, fn) { + var res = [], + i, + arrLen = arr.length; + for (i = 0; i < arrLen; ++i) { + res.push(fn(arr[i], i)); + } + return res; + } + + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } + + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } + + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } + + return a; + } + + function createUTC(input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } + + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty: false, + unusedTokens: [], + unusedInput: [], + overflow: -2, + charsLeftOver: 0, + nullInput: false, + invalidEra: null, + invalidMonth: null, + invalidFormat: false, + userInvalidated: false, + iso: false, + parsedDateParts: [], + era: null, + meridiem: null, + rfc2822: false, + weekdayMismatch: false, + }; + } + + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } + + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function (fun) { + var t = Object(this), + len = t.length >>> 0, + i; + + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + + return false; + }; + } + + function isValid(m) { + var flags = null, + parsedParts = false, + isNowValid = m._d && !isNaN(m._d.getTime()); + if (isNowValid) { + flags = getParsingFlags(m); + parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }); + isNowValid = + flags.overflow < 0 && + !flags.empty && + !flags.invalidEra && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); + if (m._strict) { + isNowValid = + isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + } + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } else { + return isNowValid; + } + return m._isValid; + } + + function createInvalid(flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } else { + getParsingFlags(m).userInvalidated = true; + } + + return m; + } + + // Plugins that add properties should also add the key here (null value), + // so we can properly clone ourselves. + var momentProperties = (hooks.momentProperties = []), + updateInProgress = false; + + function copyConfig(to, from) { + var i, + prop, + val, + momentPropertiesLen = momentProperties.length; + + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } + + if (momentPropertiesLen > 0) { + for (i = 0; i < momentPropertiesLen; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } + + return to; + } + + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } + + function isMoment(obj) { + return ( + obj instanceof Moment || (obj != null && obj._isAMomentObject != null) + ); + } + + function warn(msg) { + if ( + hooks.suppressDeprecationWarnings === false && + typeof console !== 'undefined' && + console.warn + ) { + console.warn('Deprecation warning: ' + msg); + } + } + + function deprecate(msg, fn) { + var firstTime = true; + + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = [], + arg, + i, + key, + argLen = arguments.length; + for (i = 0; i < argLen; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ': ' + arguments[0][key] + ', '; + } + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn( + msg + + '\nArguments: ' + + Array.prototype.slice.call(args).join('') + + '\n' + + new Error().stack + ); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } + + var deprecations = {}; + + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + + function isFunction(input) { + return ( + (typeof Function !== 'undefined' && input instanceof Function) || + Object.prototype.toString.call(input) === '[object Function]' + ); + } + + function set(config) { + var prop, i; + for (i in config) { + if (hasOwnProp(config, i)) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + + /\d{1,2}/.source + ); + } + + function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), + prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if ( + hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop]) + ) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; + } + + function Locale(config) { + if (config != null) { + this.set(config); + } + } + + var keys; + + if (Object.keys) { + keys = Object.keys; + } else { + keys = function (obj) { + var i, + res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + + var defaultCalendar = { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }; + + function calendar(key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; + } + + function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return ( + (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + + absNumber + ); + } + + var formattingTokens = + /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, + localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, + formatFunctions = {}, + formatTokenFunctions = {}; + + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken(token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal( + func.apply(this, arguments), + token + ); + }; + } + } + + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } + + function makeFormatFunction(format) { + var array = format.match(formattingTokens), + i, + length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = '', + i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) + ? array[i].call(mom, format) + : array[i]; + } + return output; + }; + } + + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = + formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); + } + + function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace( + localFormattingTokens, + replaceLongDateFormatTokens + ); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; + } + + var defaultLongDateFormat = { + LTS: 'h:mm:ss A', + LT: 'h:mm A', + L: 'MM/DD/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY h:mm A', + LLLL: 'dddd, MMMM D, YYYY h:mm A', + }; + + function longDateFormat(key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; + } + + this._longDateFormat[key] = formatUpper + .match(formattingTokens) + .map(function (tok) { + if ( + tok === 'MMMM' || + tok === 'MM' || + tok === 'DD' || + tok === 'dddd' + ) { + return tok.slice(1); + } + return tok; + }) + .join(''); + + return this._longDateFormat[key]; + } + + var defaultInvalidDate = 'Invalid date'; + + function invalidDate() { + return this._invalidDate; + } + + var defaultOrdinal = '%d', + defaultDayOfMonthOrdinalParse = /\d{1,2}/; + + function ordinal(number) { + return this._ordinal.replace('%d', number); + } + + var defaultRelativeTime = { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + w: 'a week', + ww: '%d weeks', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }; + + function relativeTime(number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return isFunction(output) + ? output(number, withoutSuffix, string, isFuture) + : output.replace(/%d/i, number); + } + + function pastFuture(diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); + } + + var aliases = { + D: 'date', + dates: 'date', + date: 'date', + d: 'day', + days: 'day', + day: 'day', + e: 'weekday', + weekdays: 'weekday', + weekday: 'weekday', + E: 'isoWeekday', + isoweekdays: 'isoWeekday', + isoweekday: 'isoWeekday', + DDD: 'dayOfYear', + dayofyears: 'dayOfYear', + dayofyear: 'dayOfYear', + h: 'hour', + hours: 'hour', + hour: 'hour', + ms: 'millisecond', + milliseconds: 'millisecond', + millisecond: 'millisecond', + m: 'minute', + minutes: 'minute', + minute: 'minute', + M: 'month', + months: 'month', + month: 'month', + Q: 'quarter', + quarters: 'quarter', + quarter: 'quarter', + s: 'second', + seconds: 'second', + second: 'second', + gg: 'weekYear', + weekyears: 'weekYear', + weekyear: 'weekYear', + GG: 'isoWeekYear', + isoweekyears: 'isoWeekYear', + isoweekyear: 'isoWeekYear', + w: 'week', + weeks: 'week', + week: 'week', + W: 'isoWeek', + isoweeks: 'isoWeek', + isoweek: 'isoWeek', + y: 'year', + years: 'year', + year: 'year', + }; + + function normalizeUnits(units) { + return typeof units === 'string' + ? aliases[units] || aliases[units.toLowerCase()] + : undefined; + } + + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + + return normalizedInput; + } + + var priorities = { + date: 9, + day: 11, + weekday: 11, + isoWeekday: 11, + dayOfYear: 4, + hour: 13, + millisecond: 16, + minute: 14, + month: 8, + quarter: 7, + second: 15, + weekYear: 1, + isoWeekYear: 1, + week: 5, + isoWeek: 5, + year: 1, + }; + + function getPrioritizedUnits(unitsObj) { + var units = [], + u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); + } + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; + } + + var match1 = /\d/, // 0 - 9 + match2 = /\d\d/, // 00 - 99 + match3 = /\d{3}/, // 000 - 999 + match4 = /\d{4}/, // 0000 - 9999 + match6 = /[+-]?\d{6}/, // -999999 - 999999 + match1to2 = /\d\d?/, // 0 - 99 + match3to4 = /\d\d\d\d?/, // 999 - 9999 + match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 + match1to3 = /\d{1,3}/, // 0 - 999 + match1to4 = /\d{1,4}/, // 0 - 9999 + match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 + matchUnsigned = /\d+/, // 0 - inf + matchSigned = /[+-]?\d+/, // -inf - inf + matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z + matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z + matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + matchWord = + /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, + match1to2NoLeadingZero = /^[1-9]\d?/, // 1-99 + match1to2HasZero = /^([1-9]\d|\d)/, // 0-99 + regexes; + + regexes = {}; + + function addRegexToken(token, regex, strictRegex) { + regexes[token] = isFunction(regex) + ? regex + : function (isStrict, localeData) { + return isStrict && strictRegex ? strictRegex : regex; + }; + } + + function getParseRegexForToken(token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } + + return regexes[token](config._strict, config._locale); + } + + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return regexEscape( + s + .replace('\\', '') + .replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + } + ) + ); + } + + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + function absFloor(number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } + + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; + + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + + return value; + } + + var tokens = {}; + + function addParseToken(token, callback) { + var i, + func = callback, + tokenLen; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + tokenLen = token.length; + for (i = 0; i < tokenLen; i++) { + tokens[token[i]] = func; + } + } + + function addWeekParseToken(token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } + + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } + + var YEAR = 0, + MONTH = 1, + DATE = 2, + HOUR = 3, + MINUTE = 4, + SECOND = 5, + MILLISECOND = 6, + WEEK = 7, + WEEKDAY = 8; + + // FORMATTING + + addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? zeroFill(y, 4) : '+' + y; + }); + + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); + + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + + // PARSING + + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); + + addParseToken(['YYYYY', 'YYYYYY'], YEAR); + addParseToken('YYYY', function (input, array) { + array[YEAR] = + input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); + }); + + // HELPERS + + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + + // HOOKS + + hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; + + // MOMENTS + + var getSetYear = makeGetSet('FullYear', true); + + function getIsLeapYear() { + return isLeapYear(this.year()); + } + + function makeGetSet(unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } + + function get(mom, unit) { + if (!mom.isValid()) { + return NaN; + } + + var d = mom._d, + isUTC = mom._isUTC; + + switch (unit) { + case 'Milliseconds': + return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds(); + case 'Seconds': + return isUTC ? d.getUTCSeconds() : d.getSeconds(); + case 'Minutes': + return isUTC ? d.getUTCMinutes() : d.getMinutes(); + case 'Hours': + return isUTC ? d.getUTCHours() : d.getHours(); + case 'Date': + return isUTC ? d.getUTCDate() : d.getDate(); + case 'Day': + return isUTC ? d.getUTCDay() : d.getDay(); + case 'Month': + return isUTC ? d.getUTCMonth() : d.getMonth(); + case 'FullYear': + return isUTC ? d.getUTCFullYear() : d.getFullYear(); + default: + return NaN; // Just in case + } + } + + function set$1(mom, unit, value) { + var d, isUTC, year, month, date; + + if (!mom.isValid() || isNaN(value)) { + return; + } + + d = mom._d; + isUTC = mom._isUTC; + + switch (unit) { + case 'Milliseconds': + return void (isUTC + ? d.setUTCMilliseconds(value) + : d.setMilliseconds(value)); + case 'Seconds': + return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value)); + case 'Minutes': + return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value)); + case 'Hours': + return void (isUTC ? d.setUTCHours(value) : d.setHours(value)); + case 'Date': + return void (isUTC ? d.setUTCDate(value) : d.setDate(value)); + // case 'Day': // Not real + // return void (isUTC ? d.setUTCDay(value) : d.setDay(value)); + // case 'Month': // Not used because we need to pass two variables + // return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value)); + case 'FullYear': + break; // See below ... + default: + return; // Just in case + } + + year = value; + month = mom.month(); + date = mom.date(); + date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date; + void (isUTC + ? d.setUTCFullYear(year, month, date) + : d.setFullYear(year, month, date)); + } + + // MOMENTS + + function stringGet(units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; + } + + function stringSet(units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), + i, + prioritizedLen = prioritized.length; + for (i = 0; i < prioritizedLen; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; + } + + function mod(n, x) { + return ((n % x) + x) % x; + } + + var indexOf; + + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } + + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 + ? isLeapYear(year) + ? 29 + : 28 + : 31 - ((modMonth % 7) % 2); + } + + // FORMATTING + + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); + + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); + + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); + + // PARSING + + addRegexToken('M', match1to2, match1to2NoLeadingZero); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); + }); + addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); + }); + + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); + + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); + + // LOCALES + + var defaultLocaleMonths = + 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + defaultLocaleMonthsShort = + 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, + defaultMonthsShortRegex = matchWord, + defaultMonthsRegex = matchWord; + + function localeMonths(m, format) { + if (!m) { + return isArray(this._months) + ? this._months + : this._months['standalone']; + } + return isArray(this._months) + ? this._months[m.month()] + : this._months[ + (this._months.isFormat || MONTHS_IN_FORMAT).test(format) + ? 'format' + : 'standalone' + ][m.month()]; + } + + function localeMonthsShort(m, format) { + if (!m) { + return isArray(this._monthsShort) + ? this._monthsShort + : this._monthsShort['standalone']; + } + return isArray(this._monthsShort) + ? this._monthsShort[m.month()] + : this._monthsShort[ + MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' + ][m.month()]; + } + + function handleStrictParse(monthName, format, strict) { + var i, + ii, + mom, + llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort( + mom, + '' + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeMonthsParse(monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + '^' + this.months(mom, '').replace('.', '') + '$', + 'i' + ); + this._shortMonthsParse[i] = new RegExp( + '^' + this.monthsShort(mom, '').replace('.', '') + '$', + 'i' + ); + } + if (!strict && !this._monthsParse[i]) { + regex = + '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'MMMM' && + this._longMonthsParse[i].test(monthName) + ) { + return i; + } else if ( + strict && + format === 'MMM' && + this._shortMonthsParse[i].test(monthName) + ) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } + + // MOMENTS + + function setMonth(mom, value) { + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + var month = value, + date = mom.date(); + + date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month)); + void (mom._isUTC + ? mom._d.setUTCMonth(month, date) + : mom._d.setMonth(month, date)); + return mom; + } + + function getSetMonth(value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } + } + + function getDaysInMonth() { + return daysInMonth(this.year(), this.month()); + } + + function monthsShortRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict + ? this._monthsShortStrictRegex + : this._monthsShortRegex; + } + } + + function monthsRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict + ? this._monthsStrictRegex + : this._monthsRegex; + } + } + + function computeMonthsParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom, + shortP, + longP; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortP = regexEscape(this.monthsShort(mom, '')); + longP = regexEscape(this.months(mom, '')); + shortPieces.push(shortP); + longPieces.push(longP); + mixedPieces.push(longP); + mixedPieces.push(shortP); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._monthsShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + } + + function createDate(y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); + } + } else { + date = new Date(y, m, d, h, M, s, ms); + } + + return date; + } + + function createUTCDate(y) { + var date, args; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } + + return date; + } + + // start-of-first-week - start-of-year + function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; + } + + // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, + resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear, + }; + } + + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, + resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear, + }; + } + + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } + + // FORMATTING + + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + + // PARSING + + addRegexToken('w', match1to2, match1to2NoLeadingZero); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2, match1to2NoLeadingZero); + addRegexToken('WW', match1to2, match2); + + addWeekParseToken( + ['w', 'ww', 'W', 'WW'], + function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + } + ); + + // HELPERS + + // LOCALES + + function localeWeek(mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } + + var defaultLocaleWeek = { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }; + + function localeFirstDayOfWeek() { + return this._week.dow; + } + + function localeFirstDayOfYear() { + return this._week.doy; + } + + // MOMENTS + + function getSetWeek(input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + function getSetISOWeek(input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + // FORMATTING + + addFormatToken('d', 0, 'do', 'day'); + + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); + + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); + + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); + + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); + + // PARSING + + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); + }); + addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); + }); + addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); + }); + + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); + + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); + + // HELPERS + + function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; + } + + function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } + + // LOCALES + function shiftWeekdays(ws, n) { + return ws.slice(n, 7).concat(ws.slice(0, n)); + } + + var defaultLocaleWeekdays = + 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + defaultWeekdaysRegex = matchWord, + defaultWeekdaysShortRegex = matchWord, + defaultWeekdaysMinRegex = matchWord; + + function localeWeekdays(m, format) { + var weekdays = isArray(this._weekdays) + ? this._weekdays + : this._weekdays[ + m && m !== true && this._weekdays.isFormat.test(format) + ? 'format' + : 'standalone' + ]; + return m === true + ? shiftWeekdays(weekdays, this._week.dow) + : m + ? weekdays[m.day()] + : weekdays; + } + + function localeWeekdaysShort(m) { + return m === true + ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : m + ? this._weekdaysShort[m.day()] + : this._weekdaysShort; + } + + function localeWeekdaysMin(m) { + return m === true + ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : m + ? this._weekdaysMin[m.day()] + : this._weekdaysMin; + } + + function handleStrictParse$1(weekdayName, format, strict) { + var i, + ii, + mom, + llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( + mom, + '' + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + '' + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeWeekdaysParse(weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._shortWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._minWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + } + if (!this._weekdaysParse[i]) { + regex = + '^' + + this.weekdays(mom, '') + + '|^' + + this.weekdaysShort(mom, '') + + '|^' + + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'dddd' && + this._fullWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'ddd' && + this._shortWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'dd' && + this._minWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } + + // MOMENTS + + function getSetDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + var day = get(this, 'Day'); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } + + function getSetLocaleDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } + + function getSetISODayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } + + function weekdaysRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict + ? this._weekdaysStrictRegex + : this._weekdaysRegex; + } + } + + function weekdaysShortRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict + ? this._weekdaysShortStrictRegex + : this._weekdaysShortRegex; + } + } + + function weekdaysMinRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict + ? this._weekdaysMinStrictRegex + : this._weekdaysMinRegex; + } + } + + function computeWeekdaysParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], + shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom, + minp, + shortp, + longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, '')); + shortp = regexEscape(this.weekdaysShort(mom, '')); + longp = regexEscape(this.weekdays(mom, '')); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._weekdaysShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + this._weekdaysMinStrictRegex = new RegExp( + '^(' + minPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + function hFormat() { + return this.hours() % 12 || 12; + } + + function kFormat() { + return this.hours() || 24; + } + + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, hFormat); + addFormatToken('k', ['kk', 2], 0, kFormat); + + addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + + addFormatToken('hmmss', 0, 0, function () { + return ( + '' + + hFormat.apply(this) + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); + }); + + addFormatToken('Hmmss', 0, 0, function () { + return ( + '' + + this.hours() + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + function meridiem(token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase + ); + }); + } + + meridiem('a', true); + meridiem('A', false); + + // PARSING + + function matchMeridiem(isStrict, locale) { + return locale._meridiemParse; + } + + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2, match1to2HasZero); + addRegexToken('h', match1to2, match1to2NoLeadingZero); + addRegexToken('k', match1to2, match1to2NoLeadingZero); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); + addRegexToken('kk', match1to2, match2); + + addRegexToken('hmm', match3to4); + addRegexToken('hmmss', match5to6); + addRegexToken('Hmm', match3to4); + addRegexToken('Hmmss', match5to6); + + addParseToken(['H', 'HH'], HOUR); + addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + + // LOCALES + + function localeIsPM(input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return (input + '').toLowerCase().charAt(0) === 'p'; + } + + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + getSetHour = makeGetSet('Hours', true); + + function localeMeridiem(hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } + + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse, + }; + + // internal storage for locale config files + var locales = {}, + localeFamilies = {}, + globalLocale; + + function commonPrefix(arr1, arr2) { + var i, + minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + return minl; + } + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; + } + + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, + j, + next, + locale, + split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if ( + next && + next.length >= j && + commonPrefix(split, next) >= j - 1 + ) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; + } + + function isLocaleNameSane(name) { + // Prevent names that look like filesystem paths, i.e contain '/' or '\' + // Ensure name is available and function returns boolean + return !!(name && name.match('^[^/\\\\]*$')); + } + + function loadLocale(name) { + var oldLocale = null, + aliasedRequire; + // TODO: Find a better way to register and load all the locales in Node + if ( + locales[name] === undefined && + "object" !== 'undefined' && + module && + module.exports && + isLocaleNameSane(name) + ) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = undefined; + __webpack_require__(35358)("./" + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + // mark as not found to avoid repeating expensive file require call causing high CPU + // when trying to find en-US, en_US, en-us for every format call + locales[name] = null; // null means not found + } + } + return locales[name]; + } + + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function getSetGlobalLocale(key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } else { + if (typeof console !== 'undefined' && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn( + 'Locale ' + key + ' not found. Did you forget to load it?' + ); + } + } + } + + return globalLocale._abbr; + } + + function defineLocale(name, config) { + if (config !== null) { + var locale, + parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple( + 'defineLocaleOverride', + 'use moment.updateLocale(localeName, config) to change ' + + 'an existing locale. moment.defineLocale(localeName, ' + + 'config) should only be used for creating a new locale ' + + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.' + ); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config, + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } + + function updateLocale(name, config) { + if (config != null) { + var locale, + tmpLocale, + parentConfig = baseConfig; + + if (locales[name] != null && locales[name].parentLocale != null) { + // Update existing child locale in-place to avoid memory-leaks + locales[name].set(mergeConfigs(locales[name]._config, config)); + } else { + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + if (tmpLocale == null) { + // updateLocale is called for creating a new locale + // Set abbr so it will have a name (getters return + // undefined otherwise). + config.abbr = name; + } + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + } + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } + + // returns locale data + function getLocale(key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); + } + + function listLocales() { + return keys(locales); + } + + function checkOverflow(m) { + var overflow, + a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 + ? MONTH + : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) + ? DATE + : a[HOUR] < 0 || + a[HOUR] > 24 || + (a[HOUR] === 24 && + (a[MINUTE] !== 0 || + a[SECOND] !== 0 || + a[MILLISECOND] !== 0)) + ? HOUR + : a[MINUTE] < 0 || a[MINUTE] > 59 + ? MINUTE + : a[SECOND] < 0 || a[SECOND] > 59 + ? SECOND + : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 + ? MILLISECOND + : -1; + + if ( + getParsingFlags(m)._overflowDayOfYear && + (overflow < YEAR || overflow > DATE) + ) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; + } + + // iso 8601 regex + // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) + var extendedIsoRegex = + /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, + basicIsoRegex = + /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, + tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, + isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], + ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], + ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], + ['GGGG-[W]WW', /\d{4}-W\d\d/, false], + ['YYYY-DDD', /\d{4}-\d{3}/], + ['YYYY-MM', /\d{4}-\d\d/, false], + ['YYYYYYMMDD', /[+-]\d{10}/], + ['YYYYMMDD', /\d{8}/], + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/], + ['YYYYMM', /\d{6}/, false], + ['YYYY', /\d{4}/, false], + ], + // iso time formats and regexes + isoTimes = [ + ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], + ['HH:mm:ss', /\d\d:\d\d:\d\d/], + ['HH:mm', /\d\d:\d\d/], + ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], + ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], + ['HHmmss', /\d\d\d\d\d\d/], + ['HHmm', /\d\d\d\d/], + ['HH', /\d\d/], + ], + aspNetJsonRegex = /^\/?Date\((-?\d+)/i, + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + rfc2822 = + /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, + obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60, + }; + + // date from iso format + function configFromISO(config) { + var i, + l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, + dateFormat, + timeFormat, + tzFormat, + isoDatesLen = isoDates.length, + isoTimesLen = isoTimes.length; + + if (match) { + getParsingFlags(config).iso = true; + for (i = 0, l = isoDatesLen; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimesLen; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } + + function extractFromRFC2822Strings( + yearStr, + monthStr, + dayStr, + hourStr, + minuteStr, + secondStr + ) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10), + ]; + + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + + return result; + } + + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } + + function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^()]*\)|[\n\t]/g, ' ') + .replace(/(\s\s+)/g, ' ') + .replace(/^\s\s*/, '') + .replace(/\s\s*$/, ''); + } + + function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an independent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2] + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; + } + + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10), + m = hm % 100, + h = (hm - m) / 100; + return h * 60 + m; + } + } + + // date and time from ref 2822 format + function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)), + parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7] + ); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } + } + + // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + if (config._strict) { + config._isValid = false; + } else { + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); + } + } + + hooks.createFromInputFallback = deprecate( + 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + + 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); + + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; + } + + function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate(), + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray(config) { + var i, + date, + input = [], + currentDate, + expectedWeekday, + yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if ( + config._dayOfYear > daysInYear(yearToUse) || + config._dayOfYear === 0 + ) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = + config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if ( + config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0 + ) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply( + null, + input + ); + expectedWeekday = config._useUTC + ? config._d.getUTCDay() + : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if ( + config._w && + typeof config._w.d !== 'undefined' && + config._w.d !== expectedWeekday + ) { + getParsingFlags(config).weekdayMismatch = true; + } + } + + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults( + w.GG, + config._a[YEAR], + weekOfYear(createLocal(), 1, 4).year + ); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to beginning of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } + } + + // constant that refers to the ISO standard + hooks.ISO_8601 = function () {}; + + // constant that refers to the RFC 2822 form + hooks.RFC_2822 = function () {}; + + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, + parsedInput, + tokens, + token, + skipped, + stringLength = string.length, + totalParsedInputLength = 0, + era, + tokenLen; + + tokens = + expandFormat(config._f, config._locale).match(formattingTokens) || []; + tokenLen = tokens.length; + for (i = 0; i < tokenLen; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || + [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice( + string.indexOf(parsedInput) + parsedInput.length + ); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = + stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if ( + config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0 + ) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap( + config._locale, + config._a[HOUR], + config._meridiem + ); + + // handle era + era = getParsingFlags(config).era; + if (era !== null) { + config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); + } + + configFromArray(config); + checkOverflow(config); + } + + function meridiemFixWrap(locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } + + // date from string and array of format strings + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + scoreToBeat, + i, + currentScore, + validFormatFound, + bestFormatIsValid = false, + configfLen = config._f.length; + + if (configfLen === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < configfLen; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (isValid(tempConfig)) { + validFormatFound = true; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (!bestFormatIsValid) { + if ( + scoreToBeat == null || + currentScore < scoreToBeat || + validFormatFound + ) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; + } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + } + + extend(config, bestMoment || tempConfig); + } + + function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i), + dayOrDate = i.day === undefined ? i.date : i.day; + config._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function (obj) { + return obj && parseInt(obj, 10); + } + ); + + configFromArray(config); + } + + function createFromConfig(config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; + } + + function prepareConfig(config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({ nullInput: true }); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; + } + + function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } + } + + function createLocalOrUTC(input, format, locale, strict, isUTC) { + var c = {}; + + if (format === true || format === false) { + strict = format; + format = undefined; + } + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ( + (isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0) + ) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); + } + + function createLocal(input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } + + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ), + prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); + + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } + + // TODO: Use [].sort instead? + function min() { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); + } + + function max() { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); + } + + var now = function () { + return Date.now ? Date.now() : +new Date(); + }; + + var ordering = [ + 'year', + 'quarter', + 'month', + 'week', + 'day', + 'hour', + 'minute', + 'second', + 'millisecond', + ]; + + function isDurationValid(m) { + var key, + unitHasDecimal = false, + i, + orderLen = ordering.length; + for (key in m) { + if ( + hasOwnProp(m, key) && + !( + indexOf.call(ordering, key) !== -1 && + (m[key] == null || !isNaN(m[key])) + ) + ) { + return false; + } + } + + for (i = 0; i < orderLen; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; + } + + function isValid$1() { + return this._isValid; + } + + function createInvalid$1() { + return createDuration(NaN); + } + + function Duration(duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = + +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + quarters * 3 + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); + } + + function isDuration(obj) { + return obj instanceof Duration; + } + + function absRound(number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } + + // compare two arrays, return the number of differences + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ( + (dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) + ) { + diffs++; + } + } + return diffs + lengthDiff; + } + + // FORMATTING + + function offset(token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(), + sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return ( + sign + + zeroFill(~~(offset / 60), 2) + + separator + + zeroFill(~~offset % 60, 2) + ); + }); + } + + offset('Z', ':'); + offset('ZZ', ''); + + // PARSING + + addRegexToken('Z', matchShortOffset); + addRegexToken('ZZ', matchShortOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); + }); + + // HELPERS + + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; + + function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher), + chunk, + parts, + minutes; + + if (matches === null) { + return null; + } + + chunk = matches[matches.length - 1] || []; + parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; + } + + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = + (isMoment(input) || isDate(input) + ? input.valueOf() + : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } + } + + function getDateOffset(m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset()); + } + + // HOOKS + + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + hooks.updateOffset = function () {}; + + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset(input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract( + this, + createDuration(input - offset, 'm'), + 1, + false + ); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } + } + + function getSetZone(input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } + } + + function setOffsetToUTC(keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + + function setOffsetToLocal(keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } + + function setOffsetToParsedOffset() { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); + } + } + return this; + } + + function hasAlignedHourOffset(input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; + } + + function isDaylightSavingTime() { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } + + function isDaylightSavingTimeShifted() { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}, + other; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = + this.isValid() && compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; + } + + function isLocal() { + return this.isValid() ? !this._isUTC : false; + } + + function isUtcOffset() { + return this.isValid() ? this._isUTC : false; + } + + function isUtc() { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + + // ASP.NET json date format regex + var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + isoRegex = + /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + + function createDuration(input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months, + }; + } else if (isNumber(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; + } + } else if ((match = aspNetRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign, + h: toInt(match[HOUR]) * sign, + m: toInt(match[MINUTE]) * sign, + s: toInt(match[SECOND]) * sign, + ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match + }; + } else if ((match = isoRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: parseIso(match[2], sign), + M: parseIso(match[3], sign), + w: parseIso(match[4], sign), + d: parseIso(match[5], sign), + h: parseIso(match[6], sign), + m: parseIso(match[7], sign), + s: parseIso(match[8], sign), + }; + } else if (duration == null) { + // checks for null or undefined + duration = {}; + } else if ( + typeof duration === 'object' && + ('from' in duration || 'to' in duration) + ) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to) + ); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + if (isDuration(input) && hasOwnProp(input, '_isValid')) { + ret._isValid = input._isValid; + } + + return ret; + } + + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + + function parseIso(inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } + + function positiveMomentsDifference(base, other) { + var res = {}; + + res.months = + other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +base.clone().add(res.months, 'M'); + + return res; + } + + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; + } + + // TODO: remove 'name' arg after deprecation is removed + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple( + name, + 'moment().' + + name + + '(period, number) is deprecated. Please use moment().' + + name + + '(number, period). ' + + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.' + ); + tmp = val; + val = period; + period = tmp; + } + + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; + } + + function addSubtract(mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } + } + + var add = createAdder(1, 'add'), + subtract = createAdder(-1, 'subtract'); + + function isString(input) { + return typeof input === 'string' || input instanceof String; + } + + // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined + function isMomentInput(input) { + return ( + isMoment(input) || + isDate(input) || + isString(input) || + isNumber(input) || + isNumberOrStringArray(input) || + isMomentInputObject(input) || + input === null || + input === undefined + ); + } + + function isMomentInputObject(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'years', + 'year', + 'y', + 'months', + 'month', + 'M', + 'days', + 'day', + 'd', + 'dates', + 'date', + 'D', + 'hours', + 'hour', + 'h', + 'minutes', + 'minute', + 'm', + 'seconds', + 'second', + 's', + 'milliseconds', + 'millisecond', + 'ms', + ], + i, + property, + propertyLen = properties.length; + + for (i = 0; i < propertyLen; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function isNumberOrStringArray(input) { + var arrayTest = isArray(input), + dataTypeTest = false; + if (arrayTest) { + dataTypeTest = + input.filter(function (item) { + return !isNumber(item) && isString(input); + }).length === 0; + } + return arrayTest && dataTypeTest; + } + + function isCalendarSpec(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'sameDay', + 'nextDay', + 'lastDay', + 'nextWeek', + 'lastWeek', + 'sameElse', + ], + i, + property; + + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 + ? 'sameElse' + : diff < -1 + ? 'lastWeek' + : diff < 0 + ? 'lastDay' + : diff < 1 + ? 'sameDay' + : diff < 2 + ? 'nextDay' + : diff < 7 + ? 'nextWeek' + : 'sameElse'; + } + + function calendar$1(time, formats) { + // Support for single parameter, formats only overload to the calendar function + if (arguments.length === 1) { + if (!arguments[0]) { + time = undefined; + formats = undefined; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = undefined; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = undefined; + } + } + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse', + output = + formats && + (isFunction(formats[format]) + ? formats[format].call(this, now) + : formats[format]); + + return this.format( + output || this.localeData().calendar(format, this, createLocal(now)) + ); + } + + function clone() { + return new Moment(this); + } + + function isAfter(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } + + function isBefore(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } + } + + function isBetween(from, to, units, inclusivity) { + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || '()'; + return ( + (inclusivity[0] === '(' + ? this.isAfter(localFrom, units) + : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ')' + ? this.isBefore(localTo, units) + : !this.isAfter(localTo, units)) + ); + } + + function isSame(input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return ( + this.clone().startOf(units).valueOf() <= inputMs && + inputMs <= this.clone().endOf(units).valueOf() + ); + } + } + + function isSameOrAfter(input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } + + function isSameOrBefore(input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + + function diff(input, units, asFloat) { + var that, zoneDelta, output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + switch (units) { + case 'year': + output = monthDiff(this, that) / 12; + break; + case 'month': + output = monthDiff(this, that); + break; + case 'quarter': + output = monthDiff(this, that) / 3; + break; + case 'second': + output = (this - that) / 1e3; + break; // 1000 + case 'minute': + output = (this - that) / 6e4; + break; // 1000 * 60 + case 'hour': + output = (this - that) / 36e5; + break; // 1000 * 60 * 60 + case 'day': + output = (this - that - zoneDelta) / 864e5; + break; // 1000 * 60 * 60 * 24, negate dst + case 'week': + output = (this - that - zoneDelta) / 6048e5; + break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; + } + + return asFloat ? output : absFloor(output); + } + + function monthDiff(a, b) { + if (a.date() < b.date()) { + // end-of-month calculations work correct when the start month has more + // days than the end month. + return -monthDiff(b, a); + } + // difference in months + var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, + adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; + } + + hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + + function toString() { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } + + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, + m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment( + m, + utc + ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' + : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) + .toISOString() + .replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment( + m, + utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + + /** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ + function inspect() { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment', + zone = '', + prefix, + year, + datetime, + suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + prefix = '[' + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; + datetime = '-MM-DD[T]HH:mm:ss.SSS'; + suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); + } + + function format(inputString) { + if (!inputString) { + inputString = this.isUtc() + ? hooks.defaultFormatUtc + : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } + + function from(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ to: this, from: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function fromNow(withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } + + function to(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ from: this, to: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function toNow(withoutSuffix) { + return this.to(createLocal(), withoutSuffix); + } + + // If passed a locale key, it will set the locale for this + // instance. Otherwise, it will return the locale configuration + // variables for this instance. + function locale(key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } + + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); + + function localeData() { + return this._locale; + } + + var MS_PER_SECOND = 1000, + MS_PER_MINUTE = 60 * MS_PER_SECOND, + MS_PER_HOUR = 60 * MS_PER_MINUTE, + MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + + // actual modulo - handles negative numbers (for dates before 1970): + function mod$1(dividend, divisor) { + return ((dividend % divisor) + divisor) % divisor; + } + + function localStartOfDate(y, m, d) { + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } + } + + function utcStartOfDate(y, m, d) { + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } + } + + function startOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year(), 0, 1); + break; + case 'quarter': + time = startOfDate( + this.year(), + this.month() - (this.month() % 3), + 1 + ); + break; + case 'month': + time = startOfDate(this.year(), this.month(), 1); + break; + case 'week': + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + ); + break; + case 'isoWeek': + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + ); + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date()); + break; + case 'hour': + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ); + break; + case 'minute': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case 'second': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function endOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case 'quarter': + time = + startOfDate( + this.year(), + this.month() - (this.month() % 3) + 3, + 1 + ) - 1; + break; + case 'month': + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case 'week': + time = + startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7 + ) - 1; + break; + case 'isoWeek': + time = + startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7 + ) - 1; + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case 'hour': + time = this._d.valueOf(); + time += + MS_PER_HOUR - + mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ) - + 1; + break; + case 'minute': + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case 'second': + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function valueOf() { + return this._d.valueOf() - (this._offset || 0) * 60000; + } + + function unix() { + return Math.floor(this.valueOf() / 1000); + } + + function toDate() { + return new Date(this.valueOf()); + } + + function toArray() { + var m = this; + return [ + m.year(), + m.month(), + m.date(), + m.hour(), + m.minute(), + m.second(), + m.millisecond(), + ]; + } + + function toObject() { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds(), + }; + } + + function toJSON() { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; + } + + function isValid$2() { + return isValid(this); + } + + function parsingFlags() { + return extend({}, getParsingFlags(this)); + } + + function invalidAt() { + return getParsingFlags(this).overflow; + } + + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict, + }; + } + + addFormatToken('N', 0, 0, 'eraAbbr'); + addFormatToken('NN', 0, 0, 'eraAbbr'); + addFormatToken('NNN', 0, 0, 'eraAbbr'); + addFormatToken('NNNN', 0, 0, 'eraName'); + addFormatToken('NNNNN', 0, 0, 'eraNarrow'); + + addFormatToken('y', ['y', 1], 'yo', 'eraYear'); + addFormatToken('y', ['yy', 2], 0, 'eraYear'); + addFormatToken('y', ['yyy', 3], 0, 'eraYear'); + addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); + + addRegexToken('N', matchEraAbbr); + addRegexToken('NN', matchEraAbbr); + addRegexToken('NNN', matchEraAbbr); + addRegexToken('NNNN', matchEraName); + addRegexToken('NNNNN', matchEraNarrow); + + addParseToken( + ['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], + function (input, array, config, token) { + var era = config._locale.erasParse(input, token, config._strict); + if (era) { + getParsingFlags(config).era = era; + } else { + getParsingFlags(config).invalidEra = input; + } + } + ); + + addRegexToken('y', matchUnsigned); + addRegexToken('yy', matchUnsigned); + addRegexToken('yyy', matchUnsigned); + addRegexToken('yyyy', matchUnsigned); + addRegexToken('yo', matchEraYearOrdinal); + + addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); + addParseToken(['yo'], function (input, array, config, token) { + var match; + if (config._locale._eraYearOrdinalRegex) { + match = input.match(config._locale._eraYearOrdinalRegex); + } + + if (config._locale.eraYearOrdinalParse) { + array[YEAR] = config._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } + }); + + function localeEras(m, format) { + var i, + l, + date, + eras = this._eras || getLocale('en')._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case 'string': + // truncate time + date = hooks(eras[i].since).startOf('day'); + eras[i].since = date.valueOf(); + break; + } + + switch (typeof eras[i].until) { + case 'undefined': + eras[i].until = +Infinity; + break; + case 'string': + // truncate time + date = hooks(eras[i].until).startOf('day').valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; + } + + function localeErasParse(eraName, format, strict) { + var i, + l, + eras = this.eras(), + name, + abbr, + narrow; + eraName = eraName.toUpperCase(); + + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); + + if (strict) { + switch (format) { + case 'N': + case 'NN': + case 'NNN': + if (abbr === eraName) { + return eras[i]; + } + break; + + case 'NNNN': + if (name === eraName) { + return eras[i]; + } + break; + + case 'NNNNN': + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; + } + } + } + + function localeErasConvertYear(era, year) { + var dir = era.since <= era.until ? +1 : -1; + if (year === undefined) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } + } + + function getEraName() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } + + return ''; + } + + function getEraNarrow() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } + } + + return ''; + } + + function getEraAbbr() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; + } + } + + return ''; + } + + function getEraYear() { + var i, + l, + dir, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? +1 : -1; + + // truncate time + val = this.clone().startOf('day').valueOf(); + + if ( + (eras[i].since <= val && val <= eras[i].until) || + (eras[i].until <= val && val <= eras[i].since) + ) { + return ( + (this.year() - hooks(eras[i].since).year()) * dir + + eras[i].offset + ); + } + } + + return this.year(); + } + + function erasNameRegex(isStrict) { + if (!hasOwnProp(this, '_erasNameRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; + } + + function erasAbbrRegex(isStrict) { + if (!hasOwnProp(this, '_erasAbbrRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; + } + + function erasNarrowRegex(isStrict) { + if (!hasOwnProp(this, '_erasNarrowRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; + } + + function matchEraAbbr(isStrict, locale) { + return locale.erasAbbrRegex(isStrict); + } + + function matchEraName(isStrict, locale) { + return locale.erasNameRegex(isStrict); + } + + function matchEraNarrow(isStrict, locale) { + return locale.erasNarrowRegex(isStrict); + } + + function matchEraYearOrdinal(isStrict, locale) { + return locale._eraYearOrdinalRegex || matchUnsigned; + } + + function computeErasParse() { + var abbrPieces = [], + namePieces = [], + narrowPieces = [], + mixedPieces = [], + i, + l, + erasName, + erasAbbr, + erasNarrow, + eras = this.eras(); + + for (i = 0, l = eras.length; i < l; ++i) { + erasName = regexEscape(eras[i].name); + erasAbbr = regexEscape(eras[i].abbr); + erasNarrow = regexEscape(eras[i].narrow); + + namePieces.push(erasName); + abbrPieces.push(erasAbbr); + narrowPieces.push(erasNarrow); + mixedPieces.push(erasName); + mixedPieces.push(erasAbbr); + mixedPieces.push(erasNarrow); + } + + this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); + this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); + this._erasNarrowRegex = new RegExp( + '^(' + narrowPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); + + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); + + function addWeekYearFormatToken(token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } + + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + + // ALIASES + + // PARSING + + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); + + addWeekParseToken( + ['gggg', 'ggggg', 'GGGG', 'GGGGG'], + function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + } + ); + + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); + }); + + // MOMENTS + + function getSetWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday() + this.localeData()._week.dow, + this.localeData()._week.dow, + this.localeData()._week.doy + ); + } + + function getSetISOWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4 + ); + } + + function getISOWeeksInYear() { + return weeksInYear(this.year(), 1, 4); + } + + function getISOWeeksInISOWeekYear() { + return weeksInYear(this.isoWeekYear(), 1, 4); + } + + function getWeeksInYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } + + function getWeeksInWeekYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + } + + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } + } + + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; + } + + // FORMATTING + + addFormatToken('Q', 0, 'Qo', 'quarter'); + + // PARSING + + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + + // MOMENTS + + function getSetQuarter(input) { + return input == null + ? Math.ceil((this.month() + 1) / 3) + : this.month((input - 1) * 3 + (this.month() % 3)); + } + + // FORMATTING + + addFormatToken('D', ['DD', 2], 'Do', 'date'); + + // PARSING + + addRegexToken('D', match1to2, match1to2NoLeadingZero); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict + ? locale._dayOfMonthOrdinalParse || locale._ordinalParse + : locale._dayOfMonthOrdinalParseLenient; + }); + + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + + // MOMENTS + + var getSetDayOfMonth = makeGetSet('Date', true); + + // FORMATTING + + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + + // PARSING + + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); + + // HELPERS + + // MOMENTS + + function getSetDayOfYear(input) { + var dayOfYear = + Math.round( + (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); + } + + // FORMATTING + + addFormatToken('m', ['mm', 2], 0, 'minute'); + + // PARSING + + addRegexToken('m', match1to2, match1to2HasZero); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); + + // MOMENTS + + var getSetMinute = makeGetSet('Minutes', false); + + // FORMATTING + + addFormatToken('s', ['ss', 2], 0, 'second'); + + // PARSING + + addRegexToken('s', match1to2, match1to2HasZero); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); + + // MOMENTS + + var getSetSecond = makeGetSet('Seconds', false); + + // FORMATTING + + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); + + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); + + addFormatToken(0, ['SSS', 3], 0, 'millisecond'); + addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; + }); + addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; + }); + addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; + }); + addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; + }); + addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; + }); + addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; + }); + + // PARSING + + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + + var token, getSetMillisecond; + for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); + } + + function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + } + + for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); + } + + getSetMillisecond = makeGetSet('Milliseconds', false); + + // FORMATTING + + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); + + // MOMENTS + + function getZoneAbbr() { + return this._isUTC ? 'UTC' : ''; + } + + function getZoneName() { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } + + var proto = Moment.prototype; + + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from; + proto.fromNow = fromNow; + proto.to = to; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + if (typeof Symbol !== 'undefined' && Symbol.for != null) { + proto[Symbol.for('nodejs.util.inspect.custom')] = function () { + return 'Moment<' + this.format() + '>'; + }; + } + proto.toJSON = toJSON; + proto.toString = toString; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.eraName = getEraName; + proto.eraNarrow = getEraNarrow; + proto.eraAbbr = getEraAbbr; + proto.eraYear = getEraYear; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.weeksInWeekYear = getWeeksInWeekYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate( + 'dates accessor is deprecated. Use date instead.', + getSetDayOfMonth + ); + proto.months = deprecate( + 'months accessor is deprecated. Use month instead', + getSetMonth + ); + proto.years = deprecate( + 'years accessor is deprecated. Use year instead', + getSetYear + ); + proto.zone = deprecate( + 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', + getSetZone + ); + proto.isDSTShifted = deprecate( + 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', + isDaylightSavingTimeShifted + ); + + function createUnix(input) { + return createLocal(input * 1000); + } + + function createInZone() { + return createLocal.apply(null, arguments).parseZone(); + } + + function preParsePostFormat(string) { + return string; + } + + var proto$1 = Locale.prototype; + + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + proto$1.eras = localeEras; + proto$1.erasParse = localeErasParse; + proto$1.erasConvertYear = localeErasConvertYear; + proto$1.erasAbbrRegex = erasAbbrRegex; + proto$1.erasNameRegex = erasNameRegex; + proto$1.erasNarrowRegex = erasNarrowRegex; + + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + + function get$1(format, index, field, setter) { + var locale = getLocale(), + utc = createUTC().set(setter, index); + return locale[field](utc, format); + } + + function listMonthsImpl(format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i, + out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; + } + + // () + // (5) + // (fmt, 5) + // (fmt) + // (true) + // (true, 5) + // (true, fmt, 5) + // (true, fmt) + function listWeekdaysImpl(localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0, + i, + out = []; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; + } + + function listMonths(format, index) { + return listMonthsImpl(format, index, 'months'); + } + + function listMonthsShort(format, index) { + return listMonthsImpl(format, index, 'monthsShort'); + } + + function listWeekdays(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); + } + + function listWeekdaysShort(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); + } + + function listWeekdaysMin(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); + } + + getSetGlobalLocale('en', { + eras: [ + { + since: '0001-01-01', + until: +Infinity, + offset: 1, + name: 'Anno Domini', + narrow: 'AD', + abbr: 'AD', + }, + { + since: '0000-12-31', + until: -Infinity, + offset: 1, + name: 'Before Christ', + narrow: 'BC', + abbr: 'BC', + }, + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function (number) { + var b = number % 10, + output = + toInt((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + }); + + // Side effect imports + + hooks.lang = deprecate( + 'moment.lang is deprecated. Use moment.locale instead.', + getSetGlobalLocale + ); + hooks.langData = deprecate( + 'moment.langData is deprecated. Use moment.localeData instead.', + getLocale + ); + + var mathAbs = Math.abs; + + function abs() { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; + } + + function addSubtract$1(duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); + } + + // supports only 2.0-style add(1, 's') or add(duration) + function add$1(input, value) { + return addSubtract$1(this, input, value, 1); + } + + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function subtract$1(input, value) { + return addSubtract$1(this, input, value, -1); + } + + function absCeil(number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } + } + + function bubble() { + var milliseconds = this._milliseconds, + days = this._days, + months = this._months, + data = this._data, + seconds, + minutes, + hours, + years, + monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if ( + !( + (milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0) + ) + ) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; + } + + function daysToMonths(days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return (days * 4800) / 146097; + } + + function monthsToDays(months) { + // the reverse of daysToMonths + return (months * 146097) / 4800; + } + + function as(units) { + if (!this.isValid()) { + return NaN; + } + var days, + months, + milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'quarter' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case 'month': + return months; + case 'quarter': + return months / 3; + case 'year': + return months / 12; + } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week': + return days / 7 + milliseconds / 6048e5; + case 'day': + return days + milliseconds / 864e5; + case 'hour': + return days * 24 + milliseconds / 36e5; + case 'minute': + return days * 1440 + milliseconds / 6e4; + case 'second': + return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': + return Math.floor(days * 864e5) + milliseconds; + default: + throw new Error('Unknown unit ' + units); + } + } + } + + function makeAs(alias) { + return function () { + return this.as(alias); + }; + } + + var asMilliseconds = makeAs('ms'), + asSeconds = makeAs('s'), + asMinutes = makeAs('m'), + asHours = makeAs('h'), + asDays = makeAs('d'), + asWeeks = makeAs('w'), + asMonths = makeAs('M'), + asQuarters = makeAs('Q'), + asYears = makeAs('y'), + valueOf$1 = asMilliseconds; + + function clone$1() { + return createDuration(this); + } + + function get$2(units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; + } + + function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; + } + + var milliseconds = makeGetter('milliseconds'), + seconds = makeGetter('seconds'), + minutes = makeGetter('minutes'), + hours = makeGetter('hours'), + days = makeGetter('days'), + months = makeGetter('months'), + years = makeGetter('years'); + + function weeks() { + return absFloor(this.days() / 7); + } + + var round = Math.round, + thresholds = { + ss: 44, // a few seconds to seconds + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month/week + w: null, // weeks to month + M: 11, // months to year + }; + + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } + + function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { + var duration = createDuration(posNegDuration).abs(), + seconds = round(duration.as('s')), + minutes = round(duration.as('m')), + hours = round(duration.as('h')), + days = round(duration.as('d')), + months = round(duration.as('M')), + weeks = round(duration.as('w')), + years = round(duration.as('y')), + a = + (seconds <= thresholds.ss && ['s', seconds]) || + (seconds < thresholds.s && ['ss', seconds]) || + (minutes <= 1 && ['m']) || + (minutes < thresholds.m && ['mm', minutes]) || + (hours <= 1 && ['h']) || + (hours < thresholds.h && ['hh', hours]) || + (days <= 1 && ['d']) || + (days < thresholds.d && ['dd', days]); + + if (thresholds.w != null) { + a = + a || + (weeks <= 1 && ['w']) || + (weeks < thresholds.w && ['ww', weeks]); + } + a = a || + (months <= 1 && ['M']) || + (months < thresholds.M && ['MM', months]) || + (years <= 1 && ['y']) || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } + + // This function allows you to set the rounding function for relative time strings + function getSetRelativeTimeRounding(roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof roundingFunction === 'function') { + round = roundingFunction; + return true; + } + return false; + } + + // This function allows you to set a threshold for relative time strings + function getSetRelativeTimeThreshold(threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; + } + + function humanize(argWithSuffix, argThresholds) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var withSuffix = false, + th = thresholds, + locale, + output; + + if (typeof argWithSuffix === 'object') { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === 'boolean') { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === 'object') { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; + } + } + + locale = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); + } + + var abs$1 = Math.abs; + + function sign(x) { + return (x > 0) - (x < 0) || +x; + } + + function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000, + days = abs$1(this._days), + months = abs$1(this._months), + minutes, + hours, + years, + s, + total = this.asSeconds(), + totalSign, + ymSign, + daysSign, + hmsSign; + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + + totalSign = total < 0 ? '-' : ''; + ymSign = sign(this._months) !== sign(total) ? '-' : ''; + daysSign = sign(this._days) !== sign(total) ? '-' : ''; + hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + + return ( + totalSign + + 'P' + + (years ? ymSign + years + 'Y' : '') + + (months ? ymSign + months + 'M' : '') + + (days ? daysSign + days + 'D' : '') + + (hours || minutes || seconds ? 'T' : '') + + (hours ? hmsSign + hours + 'H' : '') + + (minutes ? hmsSign + minutes + 'M' : '') + + (seconds ? hmsSign + s + 'S' : '') + ); + } + + var proto$2 = Duration.prototype; + + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + + proto$2.toIsoString = deprecate( + 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', + toISOString$1 + ); + proto$2.lang = lang; + + // FORMATTING + + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); + + // PARSING + + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); + }); + + //! moment.js + + hooks.version = '2.30.1'; + + setHookCallback(createLocal); + + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + + // currently HTML5 input type only supports 24-hour formats + hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'GGGG-[W]WW', // + MONTH: 'YYYY-MM', // + }; + + return hooks; + +}))); + + +/***/ }), + +/***/ 6585: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + + +/***/ }), + +/***/ 86889: +/***/ ((module) => { + +module.exports = assert + +class AssertionError extends Error {} +AssertionError.prototype.name = 'AssertionError' + +/** + * Minimal assert function + * @param {any} t Value to check if falsy + * @param {string=} m Optional assertion error message + * @throws {AssertionError} + */ +function assert (t, m) { + if (!t) { + var err = new AssertionError(m) + if (Error.captureStackTrace) Error.captureStackTrace(err, assert) + throw err + } +} + + +/***/ }), + +/***/ 89211: +/***/ ((module) => { + +"use strict"; + + +var numberIsNaN = function (value) { + return value !== value; +}; + +module.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; +}; + + + +/***/ }), + +/***/ 37653: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(38452); +var callBind = __webpack_require__(10487); + +var implementation = __webpack_require__(89211); +var getPolyfill = __webpack_require__(9394); +var shim = __webpack_require__(36576); + +var polyfill = callBind(getPolyfill(), Object); + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 9394: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(89211); + +module.exports = function getPolyfill() { + return typeof Object.is === 'function' ? Object.is : implementation; +}; + + +/***/ }), + +/***/ 36576: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var getPolyfill = __webpack_require__(9394); +var define = __webpack_require__(38452); + +module.exports = function shimObjectIs() { + var polyfill = getPolyfill(); + define(Object, { is: polyfill }, { + is: function testObjectIs() { + return Object.is !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 28875: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = __webpack_require__(1093); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; + + +/***/ }), + +/***/ 1189: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var slice = Array.prototype.slice; +var isArgs = __webpack_require__(1093); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(28875); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; + + +/***/ }), + +/***/ 1093: +/***/ ((module) => { + +"use strict"; + + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + + +/***/ }), + +/***/ 38403: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = __webpack_require__(1189); +var hasSymbols = __webpack_require__(41333)(); +var callBound = __webpack_require__(38075); +var toObject = Object; +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = toObject(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = toObject(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; + + +/***/ }), + +/***/ 11514: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(38403); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; + + +/***/ }), + +/***/ 51072: +/***/ ((__unused_webpack_module, exports) => { + +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +exports.homedir = function () { + return '/' +}; + + +/***/ }), + +/***/ 9805: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + + +/***/ }), + +/***/ 53269: +/***/ ((module) => { + +"use strict"; + + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + + +/***/ }), + +/***/ 19681: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + + +/***/ }), + +/***/ 14823: +/***/ ((module) => { + +"use strict"; + + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + + +/***/ }), + +/***/ 58411: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(9805); +var trees = __webpack_require__(23665); +var adler32 = __webpack_require__(53269); +var crc32 = __webpack_require__(14823); +var msg = __webpack_require__(54674); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + + +/***/ }), + +/***/ 47293: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + + +/***/ }), + +/***/ 71447: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(9805); +var adler32 = __webpack_require__(53269); +var crc32 = __webpack_require__(14823); +var inflate_fast = __webpack_require__(47293); +var inflate_table = __webpack_require__(21998); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + + +/***/ }), + +/***/ 21998: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(9805); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + + +/***/ }), + +/***/ 54674: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + + +/***/ }), + +/***/ 23665: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = __webpack_require__(9805); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + + +/***/ }), + +/***/ 44442: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + + +/***/ }), + +/***/ 21137: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + + + +var asn1 = __webpack_require__(87568); + +exports.certificate = __webpack_require__(36413); + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('modulus')['int'](), + this.key('publicExponent')['int'](), + this.key('privateExponent')['int'](), + this.key('prime1')['int'](), + this.key('prime2')['int'](), + this.key('exponent1')['int'](), + this.key('exponent2')['int'](), + this.key('coefficient')['int']() + ); +}); +exports.RSAPrivateKey = RSAPrivateKey; + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus')['int'](), + this.key('publicExponent')['int']() + ); +}); +exports.RSAPublicKey = RSAPublicKey; + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int']() + ).optional() + ); +}); + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +exports.PublicKey = PublicKey; + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.PrivateKey = PrivateKeyInfo; +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters')['int']() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ); +}); + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int'](), + this.key('pub_key')['int'](), + this.key('priv_key')['int']() + ); +}); +exports.DSAPrivateKey = DSAPrivateKey; + +exports.DSAparam = asn1.define('DSAparam', function () { + this['int'](); +}); + +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }); +}); + +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ); +}); +exports.ECPrivateKey = ECPrivateKey; + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r')['int'](), + this.key('s')['int']() + ); +}); + + +/***/ }), + +/***/ 36413: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js +// thanks to @Rantanen + + + +var asn = __webpack_require__(87568); + +var Time = asn.define('Time', function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }); +}); + +var AttributeTypeValue = asn.define('AttributeTypeValue', function () { + this.seq().obj( + this.key('type').objid(), + this.key('value').any() + ); +}); + +var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional(), + this.key('curve').objid().optional() + ); +}); + +var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); + +var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { + this.setof(AttributeTypeValue); +}); + +var RDNSequence = asn.define('RDNSequence', function () { + this.seqof(RelativeDistinguishedName); +}); + +var Name = asn.define('Name', function () { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); +}); + +var Validity = asn.define('Validity', function () { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); + +var Extension = asn.define('Extension', function () { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ); +}); + +var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0)['int']().optional(), + this.key('serialNumber')['int'](), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ); +}); + +var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ); +}); + +module.exports = X509Certificate; + + +/***/ }), + +/***/ 24101: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m; +var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m; +var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m; +var evp = __webpack_require__(68078); +var ciphers = __webpack_require__(1241); +var Buffer = (__webpack_require__(92861).Buffer); +module.exports = function (okey, password) { + var key = okey.toString(); + var match = key.match(findProc); + var decrypted; + if (!match) { + var match2 = key.match(fullRegex); + decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64'); + } else { + var suite = 'aes' + match[1]; + var iv = Buffer.from(match[2], 'hex'); + var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64'); + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key; + var out = []; + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv); + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + decrypted = Buffer.concat(out); + } + var tag = key.match(startRegex)[1]; + return { + tag: tag, + data: decrypted + }; +}; + + +/***/ }), + +/***/ 78170: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var asn1 = __webpack_require__(21137); +var aesid = __webpack_require__(15579); +var fixProc = __webpack_require__(24101); +var ciphers = __webpack_require__(1241); +var compat = __webpack_require__(78396); +var Buffer = (__webpack_require__(92861).Buffer); + +function decrypt(data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt; + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10); + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]; + var iv = data.algorithm.decrypt.cipher.iv; + var cipherText = data.subjectPrivateKey; + var keylen = parseInt(algo.split('-')[1], 10) / 8; + var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1'); + var cipher = ciphers.createDecipheriv(algo, key, iv); + var out = []; + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + return Buffer.concat(out); +} + +function parseKeys(buffer) { + var password; + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase; + buffer = buffer.key; + } + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer); + } + + var stripped = fixProc(buffer, password); + + var type = stripped.tag; + var data = stripped.data; + var subtype, ndata; + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo; + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der'); + } + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der'); + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey; + return { + type: 'ec', + data: ndata + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der'); + return { + type: 'dsa', + data: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der'); + data = decrypt(data, password); + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der'); + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der'); + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der'); + return { + type: 'dsa', + params: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der'); + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der'); + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + }; + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der'); + return { + curve: data.parameters.value, + privateKey: data.privateKey + }; + default: throw new Error('unknown key type ' + type); + } +} +parseKeys.signature = asn1.signature; + +module.exports = parseKeys; + + +/***/ }), + +/***/ 78396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.pbkdf2 = __webpack_require__(43832) +exports.pbkdf2Sync = __webpack_require__(21352) + + +/***/ }), + +/***/ 43832: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) + +var checkParameters = __webpack_require__(64196) +var defaultEncoding = __webpack_require__(2455) +var sync = __webpack_require__(21352) +var toBuffer = __webpack_require__(93382) + +var ZERO_BUF +var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle +var toBrowser = { + sha: 'SHA-1', + 'sha-1': 'SHA-1', + sha1: 'SHA-1', + sha256: 'SHA-256', + 'sha-256': 'SHA-256', + sha384: 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + sha512: 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom +} +var nextTick +function getNextTick () { + if (nextTick) { + return nextTick + } + if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) { + nextTick = __webpack_require__.g.process.nextTick + } else if (__webpack_require__.g.queueMicrotask) { + nextTick = __webpack_require__.g.queueMicrotask + } else if (__webpack_require__.g.setImmediate) { + nextTick = __webpack_require__.g.setImmediate + } else { + nextTick = __webpack_require__.g.setTimeout + } + return nextTick +} +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) +} + +function resolvePromise (promise, callback) { + promise.then(function (out) { + getNextTick()(function () { + callback(null, out) + }) + }, function (e) { + getNextTick()(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] + + if (!algo || typeof __webpack_require__.g.Promise !== 'function') { + getNextTick()(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + return + } + + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + + return sync(password, salt, iterations, keylen, digest) + }), callback) +} + + +/***/ }), + +/***/ 2455: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +var defaultEncoding +/* istanbul ignore next */ +if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { + defaultEncoding = 'utf-8' +} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} else { + defaultEncoding = 'utf-8' +} +module.exports = defaultEncoding + + +/***/ }), + +/***/ 64196: +/***/ ((module) => { + +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + + +/***/ }), + +/***/ 21352: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var md5 = __webpack_require__(20320) +var RIPEMD160 = __webpack_require__(66011) +var sha = __webpack_require__(62802) +var Buffer = (__webpack_require__(92861).Buffer) + +var checkParameters = __webpack_require__(64196) +var defaultEncoding = __webpack_require__(2455) +var toBuffer = __webpack_require__(93382) + +var ZEROS = Buffer.alloc(128) +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} + +function Hmac (alg, key, saltLen) { + var hash = getDigest(alg) + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + if (key.length > blocksize) { + key = hash(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) + ipad.copy(ipad1, 0, 0, blocksize) + this.ipad1 = ipad1 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + this.hash = hash + this.size = sizes[alg] +} + +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize) + var h = this.hash(ipad) + h.copy(this.opad, this.blocksize) + return this.hash(this.opad) +} + +function getDigest (alg) { + function shaFunc (data) { + return sha(alg).update(data).digest() + } + function rmd160Func (data) { + return new RIPEMD160().update(data).digest() + } + + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func + if (alg === 'md5') return md5 + return shaFunc +} + +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + + digest = digest || 'sha1' + + var hmac = new Hmac(digest, password, salt.length) + + var DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var T = hmac.run(block1, hmac.ipad1) + var U = T + + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2) + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + T.copy(DK, destPos) + destPos += hLen + } + + return DK +} + +module.exports = pbkdf2 + + +/***/ }), + +/***/ 93382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) + +module.exports = function (thing, encoding, name) { + if (Buffer.isBuffer(thing)) { + return thing + } else if (typeof thing === 'string') { + return Buffer.from(thing, encoding) + } else if (ArrayBuffer.isView(thing)) { + return Buffer.from(thing.buffer) + } else { + throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') + } +} + + +/***/ }), + +/***/ 71843: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +const { ErrorWithCause } = __webpack_require__(75832); // linemod-replace-with: export { ErrorWithCause } from './lib/error-with-cause.mjs'; + +const { // linemod-replace-with: export { + findCauseByReference, + getErrorCause, + messageWithCauses, + stackWithCauses, +} = __webpack_require__(94306); // linemod-replace-with: } from './lib/helpers.mjs'; + +module.exports = { // linemod-remove + ErrorWithCause, // linemod-remove + findCauseByReference, // linemod-remove + getErrorCause, // linemod-remove + stackWithCauses, // linemod-remove + messageWithCauses, // linemod-remove +}; // linemod-remove + + +/***/ }), + +/***/ 75832: +/***/ ((module) => { + +"use strict"; + + +/** @template [T=undefined] */ +class ErrorWithCause extends Error { // linemod-prefix-with: export + /** + * @param {string} message + * @param {{ cause?: T }} options + */ + constructor (message, { cause } = {}) { + super(message); + + /** @type {string} */ + this.name = ErrorWithCause.name; + if (cause) { + /** @type {T} */ + this.cause = cause; + } + /** @type {string} */ + this.message = message; + } +} + +module.exports = { // linemod-remove + ErrorWithCause, // linemod-remove +}; // linemod-remove + + +/***/ }), + +/***/ 94306: +/***/ ((module) => { + +"use strict"; + + +/** + * @template {Error} T + * @param {unknown} err + * @param {new(...args: any[]) => T} reference + * @returns {T|undefined} + */ +const findCauseByReference = (err, reference) => { // linemod-prefix-with: export + if (!err || !reference) return; + if (!(err instanceof Error)) return; + if ( + !(reference.prototype instanceof Error) && + // @ts-ignore + reference !== Error + ) return; + + /** + * Ensures we don't go circular + * + * @type {Set} + */ + const seen = new Set(); + + /** @type {Error|undefined} */ + let currentErr = err; + + while (currentErr && !seen.has(currentErr)) { + seen.add(currentErr); + + if (currentErr instanceof reference) { + return currentErr; + } + + currentErr = getErrorCause(currentErr); + } +}; + +/** + * @param {Error|{ cause?: unknown|(()=>err)}} err + * @returns {Error|undefined} + */ +const getErrorCause = (err) => { // linemod-prefix-with: export + if (!err || typeof err !== 'object' || !('cause' in err)) { + return; + } + + // VError / NError style causes + if (typeof err.cause === 'function') { + const causeResult = err.cause(); + + return causeResult instanceof Error + ? causeResult + : undefined; + } else { + return err.cause instanceof Error + ? err.cause + : undefined; + } +}; + +/** + * Internal method that keeps a track of which error we have already added, to avoid circular recursion + * + * @private + * @param {Error} err + * @param {Set} seen + * @returns {string} + */ +const _stackWithCauses = (err, seen) => { + if (!(err instanceof Error)) return ''; + + const stack = err.stack || ''; + + // Ensure we don't go circular or crazily deep + if (seen.has(err)) { + return stack + '\ncauses have become circular...'; + } + + const cause = getErrorCause(err); + + // TODO: Follow up in https://github.com/nodejs/node/issues/38725#issuecomment-920309092 on how to log stuff + + if (cause) { + seen.add(err); + return (stack + '\ncaused by: ' + _stackWithCauses(cause, seen)); + } else { + return stack; + } +}; + +/** + * @param {Error} err + * @returns {string} + */ +const stackWithCauses = (err) => _stackWithCauses(err, new Set()); // linemod-prefix-with: export + +/** + * Internal method that keeps a track of which error we have already added, to avoid circular recursion + * + * @private + * @param {Error} err + * @param {Set} seen + * @param {boolean} [skip] + * @returns {string} + */ +const _messageWithCauses = (err, seen, skip) => { + if (!(err instanceof Error)) return ''; + + const message = skip ? '' : (err.message || ''); + + // Ensure we don't go circular or crazily deep + if (seen.has(err)) { + return message + ': ...'; + } + + const cause = getErrorCause(err); + + if (cause) { + seen.add(err); + + const skipIfVErrorStyleCause = 'cause' in err && typeof err.cause === 'function'; + + return (message + + (skipIfVErrorStyleCause ? '' : ': ') + + _messageWithCauses(cause, seen, skipIfVErrorStyleCause)); + } else { + return message; + } +}; + +/** + * @param {Error} err + * @returns {string} + */ +const messageWithCauses = (err) => _messageWithCauses(err, new Set()); // linemod-prefix-with: export + +module.exports = { // linemod-remove + findCauseByReference, // linemod-remove + getErrorCause, // linemod-remove + stackWithCauses, // linemod-remove + messageWithCauses, // linemod-remove +}; // linemod-remove + + +/***/ }), + +/***/ 76578: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = [ + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' +]; + + +/***/ }), + +/***/ 33225: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 65606: +/***/ ((module) => { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ 97168: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.publicEncrypt = __webpack_require__(28902) +exports.privateDecrypt = __webpack_require__(77362) + +exports.privateEncrypt = function privateEncrypt (key, buf) { + return exports.publicEncrypt(key, buf, true) +} + +exports.publicDecrypt = function publicDecrypt (key, buf) { + return exports.privateDecrypt(key, buf, true) +} + + +/***/ }), + +/***/ 48206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var createHash = __webpack_require__(47108) +var Buffer = (__webpack_require__(92861).Buffer) + +module.exports = function (seed, len) { + var t = Buffer.alloc(0) + var i = 0 + var c + while (t.length < len) { + c = i2ops(i++) + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]) + } + return t.slice(0, len) +} + +function i2ops (c) { + var out = Buffer.allocUnsafe(4) + out.writeUInt32BE(c, 0) + return out +} + + +/***/ }), + +/***/ 82509: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(51069).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 77362: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(78170) +var mgf = __webpack_require__(48206) +var xor = __webpack_require__(52061) +var BN = __webpack_require__(82509) +var crt = __webpack_require__(67332) +var createHash = __webpack_require__(47108) +var withPublic = __webpack_require__(99247) +var Buffer = (__webpack_require__(92861).Buffer) + +module.exports = function privateDecrypt (privateKey, enc, reverse) { + var padding + if (privateKey.padding) { + padding = privateKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + + var key = parseKeys(privateKey) + var k = key.modulus.byteLength() + if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error') + } + var msg + if (reverse) { + msg = withPublic(new BN(enc), key) + } else { + msg = crt(enc, key) + } + var zBuffer = Buffer.alloc(k - msg.length) + msg = Buffer.concat([zBuffer, msg], k) + if (padding === 4) { + return oaep(key, msg) + } else if (padding === 1) { + return pkcs1(key, msg, reverse) + } else if (padding === 3) { + return msg + } else { + throw new Error('unknown padding') + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + if (msg[0] !== 0) { + throw new Error('decryption error') + } + var maskedSeed = msg.slice(1, hLen + 1) + var maskedDb = msg.slice(hLen + 1) + var seed = xor(maskedSeed, mgf(maskedDb, hLen)) + var db = xor(maskedDb, mgf(seed, k - hLen - 1)) + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error') + } + var i = hLen + while (db[i] === 0) { + i++ + } + if (db[i++] !== 1) { + throw new Error('decryption error') + } + return db.slice(i) +} + +function pkcs1 (key, msg, reverse) { + var p1 = msg.slice(0, 2) + var i = 2 + var status = 0 + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++ + break + } + } + var ps = msg.slice(2, i - 1) + + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) { + status++ + } + if (ps.length < 8) { + status++ + } + if (status) { + throw new Error('decryption error') + } + return msg.slice(i) +} +function compare (a, b) { + a = Buffer.from(a) + b = Buffer.from(b) + var dif = 0 + var len = a.length + if (a.length !== b.length) { + dif++ + len = Math.min(a.length, b.length) + } + var i = -1 + while (++i < len) { + dif += (a[i] ^ b[i]) + } + return dif +} + + +/***/ }), + +/***/ 28902: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(78170) +var randomBytes = __webpack_require__(53209) +var createHash = __webpack_require__(47108) +var mgf = __webpack_require__(48206) +var xor = __webpack_require__(52061) +var BN = __webpack_require__(82509) +var withPublic = __webpack_require__(99247) +var crt = __webpack_require__(67332) +var Buffer = (__webpack_require__(92861).Buffer) + +module.exports = function publicEncrypt (publicKey, msg, reverse) { + var padding + if (publicKey.padding) { + padding = publicKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + var key = parseKeys(publicKey) + var paddedMsg + if (padding === 4) { + paddedMsg = oaep(key, msg) + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse) + } else if (padding === 3) { + paddedMsg = new BN(msg) + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus') + } + } else { + throw new Error('unknown padding') + } + if (reverse) { + return crt(paddedMsg, key) + } else { + return withPublic(paddedMsg, key) + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var mLen = msg.length + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + var hLen2 = 2 * hLen + if (mLen > k - hLen2 - 2) { + throw new Error('message too long') + } + var ps = Buffer.alloc(k - mLen - hLen2 - 2) + var dblen = k - hLen - 1 + var seed = randomBytes(hLen) + var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)) + var maskedSeed = xor(seed, mgf(maskedDb, hLen)) + return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)) +} +function pkcs1 (key, msg, reverse) { + var mLen = msg.length + var k = key.modulus.byteLength() + if (mLen > k - 11) { + throw new Error('message too long') + } + var ps + if (reverse) { + ps = Buffer.alloc(k - mLen - 3, 0xff) + } else { + ps = nonZero(k - mLen - 3) + } + return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)) +} +function nonZero (len) { + var out = Buffer.allocUnsafe(len) + var i = 0 + var cache = randomBytes(len * 2) + var cur = 0 + var num + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len * 2) + cur = 0 + } + num = cache[cur++] + if (num) { + out[i++] = num + } + } + return out +} + + +/***/ }), + +/***/ 99247: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BN = __webpack_require__(82509) +var Buffer = (__webpack_require__(92861).Buffer) + +function withPublic (paddedMsg, key) { + return Buffer.from(paddedMsg + .toRed(BN.mont(key.modulus)) + .redPow(new BN(key.publicExponent)) + .fromRed() + .toArray()) +} + +module.exports = withPublic + + +/***/ }), + +/***/ 52061: +/***/ ((module) => { + +module.exports = function xor (a, b) { + var len = a.length + var i = -1 + while (++i < len) { + a[i] ^= b[i] + } + return a +} + + +/***/ }), + +/***/ 53209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = (__webpack_require__(92861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} + + +/***/ }), + +/***/ 76983: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +function oldBrowser () { + throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') +} +var safeBuffer = __webpack_require__(92861) +var randombytes = __webpack_require__(53209) +var Buffer = safeBuffer.Buffer +var kBufferMaxLength = safeBuffer.kMaxLength +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto +var kMaxUint32 = Math.pow(2, 32) - 1 +function assertOffset (offset, length) { + if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare + throw new TypeError('offset must be a number') + } + + if (offset > kMaxUint32 || offset < 0) { + throw new TypeError('offset must be a uint32') + } + + if (offset > kBufferMaxLength || offset > length) { + throw new RangeError('offset out of range') + } +} + +function assertSize (size, offset, length) { + if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare + throw new TypeError('size must be a number') + } + + if (size > kMaxUint32 || size < 0) { + throw new TypeError('size must be a uint32') + } + + if (size + offset > length || size > kBufferMaxLength) { + throw new RangeError('buffer too small') + } +} +if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync +} else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser +} +function randomFill (buf, offset, size, cb) { + if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + if (typeof offset === 'function') { + cb = offset + offset = 0 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) +} + +function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf +} +function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + assertOffset(offset, buf.length) + + if (size === undefined) size = buf.length - offset + + assertSize(size, offset, buf.length) + + return actualFill(buf, offset, size) +} + + +/***/ }), + +/***/ 86048: +/***/ ((module) => { + +"use strict"; + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.F = codes; + + +/***/ }), + +/***/ 25382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = __webpack_require__(45412); +var Writable = __webpack_require__(16708); +__webpack_require__(56698)(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +/***/ }), + +/***/ 63600: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; +var Transform = __webpack_require__(74610); +__webpack_require__(56698)(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 45412: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(37007).EventEmitter); +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(40345); +/**/ + +var Buffer = (__webpack_require__(48287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = __webpack_require__(79838); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = __webpack_require__(80345); +var destroyImpl = __webpack_require__(75896); +var _require = __webpack_require__(65291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(86048)/* .codes */ .F), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +__webpack_require__(56698)(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(25382); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__webpack_require__(83141)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(25382); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__webpack_require__(83141)/* .StringDecoder */ .I); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __webpack_require__(2955); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __webpack_require__(55157); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 74610: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; +var _require$codes = (__webpack_require__(86048)/* .codes */ .F), + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = __webpack_require__(25382); +__webpack_require__(56698)(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} + +/***/ }), + +/***/ 16708: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: __webpack_require__(94643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(40345); +/**/ + +var Buffer = (__webpack_require__(48287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = __webpack_require__(75896); +var _require = __webpack_require__(65291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(86048)/* .codes */ .F), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +__webpack_require__(56698)(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(25382); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || __webpack_require__(25382); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; + +/***/ }), + +/***/ 2955: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = __webpack_require__(86238); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; + +/***/ }), + +/***/ 80345: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = __webpack_require__(48287), + Buffer = _require.Buffer; +var _require2 = __webpack_require__(15340), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); + +/***/ }), + +/***/ 75896: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; + +/***/ }), + +/***/ 86238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + + +var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(86048)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; + +/***/ }), + +/***/ 55157: +/***/ ((module) => { + +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + + +/***/ }), + +/***/ 57758: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = (__webpack_require__(86048)/* .codes */ .F), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __webpack_require__(86238); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; + +/***/ }), + +/***/ 65291: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__webpack_require__(86048)/* .codes */ .F).ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; + +/***/ }), + +/***/ 40345: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(37007).EventEmitter; + + +/***/ }), + +/***/ 28399: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(45412); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(16708); +exports.Duplex = __webpack_require__(25382); +exports.Transform = __webpack_require__(74610); +exports.PassThrough = __webpack_require__(63600); +exports.finished = __webpack_require__(86238); +exports.pipeline = __webpack_require__(57758); + + +/***/ }), + +/***/ 66011: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(48287).Buffer) +var inherits = __webpack_require__(56698) +var HashBase = __webpack_require__(51147) + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} + +module.exports = RIPEMD160 + + +/***/ }), + +/***/ 51147: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(92861).Buffer) +var Transform = (__webpack_require__(28399).Transform) +var inherits = __webpack_require__(56698) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + + +/***/ }), + +/***/ 92861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(48287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 93904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = __webpack_require__(98587) +const { safeRe: re, t } = __webpack_require__(99718) +const cmp = __webpack_require__(72111) +const debug = __webpack_require__(57272) +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) + + +/***/ }), + +/***/ 78311: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => comps.join(' ').trim()) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = __webpack_require__(69749) +const cache = new LRU({ max: 1000 }) + +const parseOptions = __webpack_require__(98587) +const Comparator = __webpack_require__(93904) +const debug = __webpack_require__(57272) +const SemVer = __webpack_require__(53908) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __webpack_require__(99718) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(16874) + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + + +/***/ }), + +/***/ 53908: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const debug = __webpack_require__(57272) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(16874) +const { safeRe: re, t } = __webpack_require__(99718) + +const parseOptions = __webpack_require__(98587) +const { compareIdentifiers } = __webpack_require__(61123) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer + + +/***/ }), + +/***/ 57414: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(30144) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean + + +/***/ }), + +/***/ 72111: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const eq = __webpack_require__(94641) +const neq = __webpack_require__(13999) +const gt = __webpack_require__(35580) +const gte = __webpack_require__(54089) +const lt = __webpack_require__(7059) +const lte = __webpack_require__(25200) + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp + + +/***/ }), + +/***/ 46170: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const parse = __webpack_require__(30144) +const { safeRe: re, t } = __webpack_require__(99718) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce + + +/***/ }), + +/***/ 40909: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild + + +/***/ }), + +/***/ 11763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose + + +/***/ }), + +/***/ 50560: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare + + +/***/ }), + +/***/ 51832: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(30144) + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // Otherwise it can be determined by checking the high version + + if (highVersion.patch) { + // anything higher than a patch bump would result in the wrong version + return 'patch' + } + + if (highVersion.minor) { + // anything higher than a minor bump would result in the wrong version + return 'minor' + } + + // bumping major/minor/patch all have same result + return 'major' + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff + + +/***/ }), + +/***/ 94641: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq + + +/***/ }), + +/***/ 35580: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt + + +/***/ }), + +/***/ 54089: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte + + +/***/ }), + +/***/ 93007: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc + + +/***/ }), + +/***/ 7059: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt + + +/***/ }), + +/***/ 25200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte + + +/***/ }), + +/***/ 32938: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major + + +/***/ }), + +/***/ 46254: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor + + +/***/ }), + +/***/ 13999: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq + + +/***/ }), + +/***/ 30144: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse + + +/***/ }), + +/***/ 24493: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch + + +/***/ }), + +/***/ 31729: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(30144) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease + + +/***/ }), + +/***/ 9970: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(50560) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare + + +/***/ }), + +/***/ 74277: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compareBuild = __webpack_require__(40909) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort + + +/***/ }), + +/***/ 97638: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies + + +/***/ }), + +/***/ 43927: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compareBuild = __webpack_require__(40909) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort + + +/***/ }), + +/***/ 56953: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(30144) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid + + +/***/ }), + +/***/ 99589: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// just pre-load all the stuff that index.js lazily exports +const internalRe = __webpack_require__(99718) +const constants = __webpack_require__(16874) +const SemVer = __webpack_require__(53908) +const identifiers = __webpack_require__(61123) +const parse = __webpack_require__(30144) +const valid = __webpack_require__(56953) +const clean = __webpack_require__(57414) +const inc = __webpack_require__(93007) +const diff = __webpack_require__(51832) +const major = __webpack_require__(32938) +const minor = __webpack_require__(46254) +const patch = __webpack_require__(24493) +const prerelease = __webpack_require__(31729) +const compare = __webpack_require__(50560) +const rcompare = __webpack_require__(9970) +const compareLoose = __webpack_require__(11763) +const compareBuild = __webpack_require__(40909) +const sort = __webpack_require__(43927) +const rsort = __webpack_require__(74277) +const gt = __webpack_require__(35580) +const lt = __webpack_require__(7059) +const eq = __webpack_require__(94641) +const neq = __webpack_require__(13999) +const gte = __webpack_require__(54089) +const lte = __webpack_require__(25200) +const cmp = __webpack_require__(72111) +const coerce = __webpack_require__(46170) +const Comparator = __webpack_require__(93904) +const Range = __webpack_require__(78311) +const satisfies = __webpack_require__(97638) +const toComparators = __webpack_require__(77631) +const maxSatisfying = __webpack_require__(19628) +const minSatisfying = __webpack_require__(270) +const minVersion = __webpack_require__(41261) +const validRange = __webpack_require__(13874) +const outside = __webpack_require__(97075) +const gtr = __webpack_require__(75571) +const ltr = __webpack_require__(5342) +const intersects = __webpack_require__(76780) +const simplifyRange = __webpack_require__(72525) +const subset = __webpack_require__(75032) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} + + +/***/ }), + +/***/ 16874: +/***/ ((module) => { + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} + + +/***/ }), + +/***/ 57272: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +/* provided dependency */ var console = __webpack_require__(96763); +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug + + +/***/ }), + +/***/ 61123: +/***/ ((module) => { + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} + + +/***/ }), + +/***/ 98587: +/***/ ((module) => { + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions + + +/***/ }), + +/***/ 99718: +/***/ ((module, exports, __webpack_require__) => { + +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = __webpack_require__(16874) +const debug = __webpack_require__(57272) +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') + + +/***/ }), + +/***/ 75571: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Determine if version is greater than all the versions possible in the range. +const outside = __webpack_require__(97075) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr + + +/***/ }), + +/***/ 76780: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects + + +/***/ }), + +/***/ 5342: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const outside = __webpack_require__(97075) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr + + +/***/ }), + +/***/ 19628: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying + + +/***/ }), + +/***/ 270: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying + + +/***/ }), + +/***/ 41261: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) +const gt = __webpack_require__(35580) + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion + + +/***/ }), + +/***/ 97075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Comparator = __webpack_require__(93904) +const { ANY } = Comparator +const Range = __webpack_require__(78311) +const satisfies = __webpack_require__(97638) +const gt = __webpack_require__(35580) +const lt = __webpack_require__(7059) +const lte = __webpack_require__(25200) +const gte = __webpack_require__(54089) + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside + + +/***/ }), + +/***/ 72525: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __webpack_require__(97638) +const compare = __webpack_require__(50560) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} + + +/***/ }), + +/***/ 75032: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) +const Comparator = __webpack_require__(93904) +const { ANY } = Comparator +const satisfies = __webpack_require__(97638) +const compare = __webpack_require__(50560) + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset + + +/***/ }), + +/***/ 77631: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators + + +/***/ }), + +/***/ 13874: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange + + +/***/ }), + +/***/ 96897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(70453); +var define = __webpack_require__(30041); +var hasDescriptors = __webpack_require__(30592)(); +var gOPD = __webpack_require__(75795); + +var $TypeError = __webpack_require__(69675); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + + +/***/ }), + +/***/ 90392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(92861).Buffer) + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + + +/***/ }), + +/***/ 62802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = __webpack_require__(27816) +exports.sha1 = __webpack_require__(63737) +exports.sha224 = __webpack_require__(26710) +exports.sha256 = __webpack_require__(24107) +exports.sha384 = __webpack_require__(32827) +exports.sha512 = __webpack_require__(82890) + + +/***/ }), + +/***/ 27816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + + +/***/ }), + +/***/ 63737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + + +/***/ }), + +/***/ 26710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = __webpack_require__(56698) +var Sha256 = __webpack_require__(24107) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + + +/***/ }), + +/***/ 24107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var K = [ + 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 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + 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 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + + +/***/ }), + +/***/ 32827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698) +var SHA512 = __webpack_require__(82890) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + + +/***/ }), + +/***/ 82890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + + +/***/ }), + +/***/ 88310: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = (__webpack_require__(37007).EventEmitter); +var inherits = __webpack_require__(56698); + +inherits(Stream, EE); +Stream.Readable = __webpack_require__(45412); +Stream.Writable = __webpack_require__(16708); +Stream.Duplex = __webpack_require__(25382); +Stream.Transform = __webpack_require__(74610); +Stream.PassThrough = __webpack_require__(63600); +Stream.finished = __webpack_require__(86238) +Stream.pipeline = __webpack_require__(57758) + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + + +/***/ }), + +/***/ 11568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ClientRequest = __webpack_require__(55537) +var response = __webpack_require__(6917) +var extend = __webpack_require__(57510) +var statusCodes = __webpack_require__(86866) +var url = __webpack_require__(59817) + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = __webpack_require__.g.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] + +/***/ }), + +/***/ 6688: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.fetch = isFunction(__webpack_require__.g.fetch) && isFunction(__webpack_require__.g.ReadableStream) + +exports.writableStream = isFunction(__webpack_require__.g.WritableStream) + +exports.abortController = isFunction(__webpack_require__.g.AbortController) + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (__webpack_require__.g.XMLHttpRequest) { + xhr = new __webpack_require__.g.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', __webpack_require__.g.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer') + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + + +/***/ }), + +/***/ 55537: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +/* provided dependency */ var process = __webpack_require__(65606); +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(56698) +var response = __webpack_require__(6917) +var stream = __webpack_require__(28399) + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + self._socketTimeout = null + self._socketTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + if ('timeout' in opts && opts.timeout !== 0) { + self.setTimeout(opts.timeout) + } + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + body = new Blob(self._body, { + type: (headersObj['content-type'] || {}).value || '' + }); + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = __webpack_require__.g.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + __webpack_require__.g.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._resetTimers(false) + self._connect() + }, function (reason) { + self._resetTimers(true) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new __webpack_require__.g.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self._resetTimers(true) + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + self._resetTimers(false) + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress(self._resetTimers.bind(self)) +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self)) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype._resetTimers = function (done) { + var self = this + + __webpack_require__.g.clearTimeout(self._socketTimer) + self._socketTimer = null + + if (done) { + __webpack_require__.g.clearTimeout(self._fetchTimer) + self._fetchTimer = null + } else if (self._socketTimeout) { + self._socketTimer = __webpack_require__.g.setTimeout(function () { + self.emit('timeout') + }, self._socketTimeout) + } +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) { + var self = this + self._destroyed = true + self._resetTimers(true) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() + + if (err) + self.emit('error', err) +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.setTimeout = function (timeout, cb) { + var self = this + + if (cb) + self.once('timeout', cb) + + self._socketTimeout = timeout + self._resetTimers(false) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + + +/***/ }), + +/***/ 6917: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(56698) +var stream = __webpack_require__(28399) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + resetTimers(false) + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(Buffer.from(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + resetTimers(true) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + resetTimers(result.done) + if (result.done) { + self.push(null) + return + } + self.push(Buffer.from(result.value)) + read() + }).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function (resetTimers) { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text': + response = xhr.responseText + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = Buffer.alloc(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(Buffer.from(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(Buffer.from(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new __webpack_require__.g.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + resetTimers(true) + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + resetTimers(true) + self.push(null) + } +} + + +/***/ }), + +/***/ 83141: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = (__webpack_require__(92861).Buffer); +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.I = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 76386: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +// Written in 2014-2016 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +(function(root, f) { + 'use strict'; + if ( true && module.exports) module.exports = f(); + else if (root.nacl) root.nacl.util = f(); + else { + root.nacl = {}; + root.nacl.util = f(); + } +}(this, function() { + 'use strict'; + + var util = {}; + + function validateBase64(s) { + if (!(/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(s))) { + throw new TypeError('invalid encoding'); + } + } + + util.decodeUTF8 = function(s) { + if (typeof s !== 'string') throw new TypeError('expected string'); + var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length); + for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); + return b; + }; + + util.encodeUTF8 = function(arr) { + var i, s = []; + for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i])); + return decodeURIComponent(escape(s.join(''))); + }; + + if (typeof atob === 'undefined') { + // Node.js + + if (typeof Buffer.from !== 'undefined') { + // Node v6 and later + util.encodeBase64 = function (arr) { // v6 and later + return Buffer.from(arr).toString('base64'); + }; + + util.decodeBase64 = function (s) { + validateBase64(s); + return new Uint8Array(Array.prototype.slice.call(Buffer.from(s, 'base64'), 0)); + }; + + } else { + // Node earlier than v6 + util.encodeBase64 = function (arr) { // v6 and later + return (new Buffer(arr)).toString('base64'); + }; + + util.decodeBase64 = function(s) { + validateBase64(s); + return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0)); + }; + } + + } else { + // Browsers + + util.encodeBase64 = function(arr) { + var i, s = [], len = arr.length; + for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i])); + return btoa(s.join('')); + }; + + util.decodeBase64 = function(s) { + validateBase64(s); + var i, d = atob(s), b = new Uint8Array(d.length); + for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); + return b; + }; + + } + + return util; + +})); + + +/***/ }), + +/***/ 88947: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(71281); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 46579: +/***/ (function(__unused_webpack_module, exports) { + +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; + +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=uri.all.js.map + + +/***/ }), + +/***/ 94643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!__webpack_require__.g.localStorage) return false; + } catch (_) { + return false; + } + var val = __webpack_require__.g.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + + +/***/ }), + +/***/ 81135: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), + +/***/ 49032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +var isArgumentsObject = __webpack_require__(47244); +var isGeneratorFunction = __webpack_require__(48184); +var whichTypedArray = __webpack_require__(25767); +var isTypedArray = __webpack_require__(35680); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === 'undefined') { + return false; + } + + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBufferCopy; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + + +/***/ }), + +/***/ 40537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +/* provided dependency */ var console = __webpack_require__(96763); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').slice(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = __webpack_require__(49032); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(81135); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(56698); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + + +/***/ }), + +/***/ 68961: +/***/ ((__unused_webpack_module, exports) => { + +var indexOf = function (xs, item) { + if (xs.indexOf) return xs.indexOf(item); + else for (var i = 0; i < xs.length; i++) { + if (xs[i] === item) return i; + } + return -1; +}; +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } +}()); + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; + } + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; + } + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); + } + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + if (context) { + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; + }); + } + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.isContext = function (context) { + return context instanceof Context; +}; + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + return copy; +}; + + +/***/ }), + +/***/ 14400: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +module.exports.ModuleBuilder = __webpack_require__(80442); +/* unused reexport */ __webpack_require__(38269); +/* unused reexport */ __webpack_require__(77831); + + +/***/ }), + +/***/ 65705: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const utils = __webpack_require__(60484); + +class CodeBuilder { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x21, ...utils.varuint32( idx )]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x22, ...utils.varuint32( idx )]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [0x20, ...utils.varuint32( idx )]; + } + + i64_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x30, align, ...utils.varuint32(offset)]; + } + + i64_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x31, align, ...utils.varuint32(offset)]; + } + + i64_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x32, align, ...utils.varuint32(offset)]; + } + + i64_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x33, align, ...utils.varuint32(offset)]; + } + + i64_load32_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x34, align, ...utils.varuint32(offset)]; + } + + i64_load32_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x35, align, ...utils.varuint32(offset)]; + } + + i64_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default + return [...idxCode, 0x29, align, ...utils.varuint32(offset)]; + } + + + i64_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 3; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 3; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)]; + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)]; + } + + + i64_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3d, align, ...utils.varuint32(offset)]; + } + + + i64_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3c, align, ...utils.varuint32(offset)]; + } + + i32_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2c, align, ...utils.varuint32(offset)]; + } + + i32_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2d, align, ...utils.varuint32(offset)]; + } + + i32_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2e, align, ...utils.varuint32(offset)]; + } + + i32_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2f, align, ...utils.varuint32(offset)]; + } + + i32_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x28, align, ...utils.varuint32(offset)]; + } + + i32_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)]; + } + + + i32_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3b, align, ...utils.varuint32(offset)]; + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3a, align, ...utils.varuint32(offset)]; + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [...[].concat(...args), 0x10, ...utils.varuint32(idx)]; + } + + call_indirect(fnIdx, ...args) { + return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; + } else { + return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; + } + } + + block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } + loop(...args) { + return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; + } + br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; } + br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; } + ret(rCode) { return [...rCode, 0x0f]; } + drop(dCode) { return [...dCode, 0x1a]; } + + i64_const(num) { return [0x42, ...utils.varint64(num)]; } + i32_const(num) { return [0x41, ...utils.varint32(num)]; } + + + i64_eqz(opcode) { return [...opcode, 0x50]; } + i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } + i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } + i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } + i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } + i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } + i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } + i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } + i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } + i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } + i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } + i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } + i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } + i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } + i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } + i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } + i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } + i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } + i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } + i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } + i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } + i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } + i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } + i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } + i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } + i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } + i64_clz(op1code) { return [...op1code, 0x79]; } + i64_ctz(op1code) { return [...op1code, 0x7a]; } + + i32_eqz(op1code) { return [...op1code, 0x45]; } + i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } + i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } + i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } + i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } + i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } + i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } + i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } + i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } + i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } + i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } + i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } + i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } + i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } + i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } + i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } + i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } + i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } + i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } + i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } + i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } + i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } + i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } + i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } + i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } + i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } + i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } + i32_clz(op1code) { return [...op1code, 0x67]; } + i32_ctz(op1code) { return [...op1code, 0x68]; } + + unreachable() { return [ 0x0 ]; } + + current_memory() { return [ 0x3f, 0]; } + + comment() { return []; } +} + +module.exports = CodeBuilder; + + +/***/ }), + +/***/ 24010: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const utils = __webpack_require__(60484); + +class CodeBuilderWat { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [valCode, `set_local $${localName}`]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [valCode, `tee_local $${localName}`]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return `get_local $${localName}`; + } + + genLoad(inst, def_align, idxCode, _offset, _align) { + let S = inst; + const offset = _offset || 0; + if (offset>0) S += ` offset=${offset}`; + const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default + if (align!=def_align) S += ` align=${1 << align}`; + return [idxCode, S]; + } + + + genStore(inst, def_align, idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (typeof _align === "undefined") { + offset = 0; + align = def_align; + codeVal = _offset; + } else if (typeof _codeVal === "undefined") { + offset = _offset; + align = def_align; + codeVal = _align; + } else { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + let S = inst; + if (offset>0) S += ` offset=${offset}`; + if (align!=def_align) S += ` align=${1 << align}`; + return [idxCode, codeVal, S]; + } + + i64_load8_s(idxCode, _offset, _align) { + return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align); + } + + i64_load8_u(idxCode, _offset, _align) { + return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align); + } + + i64_load16_s(idxCode, _offset, _align) { + return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align); + } + + i64_load16_u(idxCode, _offset, _align) { + return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align); + } + + i64_load32_s(idxCode, _offset, _align) { + return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align); + } + + i64_load32_u(idxCode, _offset, _align) { + return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align); + } + + i64_load(idxCode, _offset, _align) { + return this.genLoad("i64.load", 3, idxCode, _offset, _align); + } + + + i64_store(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal); + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal); + } + + i64_store16(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal); + } + + i64_store8(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal); + } + + i32_load8_s(idxCode, _offset, _align) { + return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align); + } + + i32_load8_u(idxCode, _offset, _align) { + return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align); + } + + i32_load16_s(idxCode, _offset, _align) { + return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align); + } + + i32_load16_u(idxCode, _offset, _align) { + return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align); + } + + i32_load(idxCode, _offset, _align) { + return this.genLoad("i32.load", 2, idxCode, _offset, _align); + } + + i32_store(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal); + } + + i32_store16(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal); + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal); + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [args, `call $${fnName}`]; + } + + call_indirect(fnIdx, ...args) { + return [args, fnIdx, "call_indirect (type 0)"]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [condCode, "if", utils.ident(thenCode), "else", utils.ident(elseCode), "end"]; + } else { + return [condCode, "if", utils.ident(thenCode), "end"]; + } + } + + block(bCode) { return ["block", utils.ident(bCode), "end"]; } + loop(...args) { return ["loop", utils.ident(args), "end"]; } + br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; } + br(relPath) { return `br ${relPath}`; } + ret(rCode) { return [rCode, "return"]; } + drop(dCode) { return [dCode, "drop"]; } + + i64_const(num) { return `i64.const ${num}`; } + i32_const(num) { return `i32.const ${num}`; } + + i64_eqz(opcode) { return [opcode, "i64.eqz"]; } + i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; } + i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; } + i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; } + i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; } + i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; } + i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; } + i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; } + i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; } + i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; } + i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; } + i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; } + i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; } + i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; } + i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; } + i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; } + i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; } + i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; } + i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; } + i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; } + i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; } + i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; } + i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; } + i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; } + i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; } + i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; } + + + i32_eqz(op1code) { return [op1code, "i32.eqz"]; } + i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; } + i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; } + i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; } + i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; } + i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; } + i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; } + i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; } + i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; } + i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; } + i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; } + i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; } + i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; } + i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; } + i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; } + i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; } + i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; } + i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; } + i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; } + i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; } + i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; } + i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; } + i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; } + i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; } + i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; } + i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; } + i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; } + + ureachable() { return "unreachable"; } + + current_memory() { return "current_memory"; } + + comment(c) { return ";; " + c; } + +} + +module.exports = CodeBuilderWat; + + +/***/ }), + +/***/ 55986: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const CodeBuilder = __webpack_require__(65705); +const utils = __webpack_require__(60484); + +const typeCodes = { + "i32": 0x7f, + "i64": 0x7e, + "f32": 0x7d, + "f64": 0x7c, + "anyfunc": 0x70, + "func": 0x60, + "emptyblock": 0x40 +}; + + +class FunctionBuilder { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType + }); + } + + addLocal(localName, localType, _length) { + const length = _length || 1; + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + length: length + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; + const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; + return [0x60, ...params, ...returns]; + } + + getBody() { + const locals = this.locals.map((l) => [ + ...utils.varuint32(l.length), + typeCodes[l.type] + ]); + + const body = [ + ...utils.varuint32(this.locals.length), + ...[].concat(...locals), + ...this.code, + 0x0b + ]; + return [ + ...utils.varuint32(body.length), + ...body + ]; + } + + addCode(...code) { + this.code.push(...[].concat(...[...code])); + } + + getCodeBuilder() { + return new CodeBuilder(this); + } +} + +module.exports = FunctionBuilder; + + +/***/ }), + +/***/ 42341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const CodeBuilderWat = __webpack_require__(24010); +const utils = __webpack_require__(60484); + +class FunctionBuilderWat { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + this.comment = moduleName; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType, + name: paramName + }); + } + + addLocal(localName, localType, _length) { + if ((typeof _length != "undefined") && (_length != 1)) { + throw new Error("Locals greater than 1 not implemented"); + } + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + name: localName, + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + let p = ""; + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const FunctionBuilder = __webpack_require__(55986); +const utils = __webpack_require__(60484); + +class ModuleBuilder { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + this._setSignatures(); + return new Uint8Array([ + ...utils.u32(0x6d736100), + ...utils.u32(1), + ...this._buildType(), + ...this._buildImport(), + ...this._buildFunctionDeclarations(), + ...this._buildFunctionsTable(), + ...this._buildExports(), + ...this._buildElements(), + ...this._buildCode(), + ...this._buildData() + ]); + } + + addFunction(fnName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "internal")); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new globalThis.TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = "s_"+utils.toHexString(signature); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i { + +/* provided dependency */ var Buffer = __webpack_require__(48287)["Buffer"]; +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const FunctionBuilderWat = __webpack_require__(42341); +const utils = __webpack_require__(60484); + +class ModuleBuilderWat { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + const src = []; + this._setSignatures(); + src.push(this._buildType()); + src.push(this._buildImport()); + if (this.functionsTable.length>0) { + src.push(this._buildFunctionsTable()); + } + if (this.exports.length > 0) { + src.push(this._buildExports()); + } + if (this.functionsTable.length>0) { + src.push(this._buildElements()); + } + if (this.nInternalFunctions>0) { + src.push(this._buildFunctions()); + } + src.push(this._buildData()); + return [ + "(module", + utils.ident(src), + ")" + ]; + } + + addFunction(fnName, comment) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment)); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = this.functions[this.functionsTable[0]].getSignatureName(); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i126 || b[i] == 34 || b[i]==92) { + let h=b[i].toString(16); + while (h.length<2) h = "0"+h; + S += "\\" + h; + } else { + S += String.fromCharCode(b[i]); + } + } + S += "\""; + return S; + } + } + +} + +module.exports = ModuleBuilderWat; + + +/***/ }), + +/***/ 77831: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(96763); +/* + Copyright 2019 0KIMS association. + + This file is part of websnark (Web Assembly zkSnark Prover). + + websnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + websnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with websnark. If not, see . +*/ + +/* globals WebAssembly */ +const bigInt = __webpack_require__(92096); +const ModuleBuilder = __webpack_require__(80442); + +function buf2hex(buffer) { // buffer is an ArrayBuffer + return Array.prototype.map.call(new Uint8Array(buffer), x => ("00" + x.toString(16)).slice(-2)).join(""); +} + + +async function buildProtoboard(builder, defBytes, bitsPerBytes) { + const protoboard = new Protoboard(); + + protoboard.defBytes = defBytes; + protoboard.bitsPerBytes = bitsPerBytes || 32; + + protoboard.memory = new WebAssembly.Memory({initial:20000}); + protoboard.i32 = new Uint32Array(protoboard.memory.buffer); + protoboard.i8 = new Uint8Array(protoboard.memory.buffer); + + const moduleBuilder = new ModuleBuilder(); + + const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32"); + fLog32.addParam("x", "i32"); + const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64"); + fLog64.addParam("x", "i32"); + fLog64.addParam("y", "i32"); + + buildLog32(moduleBuilder); + buildLog64(moduleBuilder); + + builder(moduleBuilder, protoboard); + + + const code = moduleBuilder.build(); + + const wasmModule = await WebAssembly.compile(code); + + protoboard.log = console.log; + + protoboard.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": protoboard.memory + }, + debug: { + log32: function (c1) { + if (c1<0) c1 = 0x100000000+c1; + let s=c1.toString(16); + while (s.length<8) s = "0"+s; + protoboard.log(s + ": " + c1.toString()); + }, + log64: function (c1, c2) { + if (c1<0) c1 = 0x100000000+c1; + if (c2<0) c2 = 0x100000000+c2; + const n = bigInt(c1) + bigInt(c2).shiftLeft(32); + let s=n.toString(16); + while (s.length<16) s = "0"+s; + protoboard.log(s + ": " + n.toString()); + } + } + }); + + Object.assign(protoboard, protoboard.instance.exports); + Object.assign(protoboard, moduleBuilder.modules); + + return protoboard; + + function buildLog32(module) { + + const f = module.addFunction("log32"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call("debug_log32", c.getLocal("x"))); + } + + function buildLog64(module) { + + const f = module.addFunction("log64"); + f.addParam("x", "i64"); + + const c = f.getCodeBuilder(); + f.addCode(c.call( + "debug_log64", + c.i32_wrap_i64(c.getLocal("x")), + c.i32_wrap_i64( + c.i64_shr_u( + c.getLocal("x"), + c.i64_const(32) + ) + ) + )); + } + +} + +class Protoboard { + + constructor() { + + } + + alloc(length) { + if (typeof length === "undefined") { + length = this.defBytes; + } + length = (((length-1)>>3) +1)<<3; // Align to 64 bits. + + const res = this.i32[0]; + this.i32[0] += length; + return res; + } + + set(pos, nums, nBytes) { + if (!Array.isArray(nums)) { + nums = [nums]; + } + if (typeof nBytes === "undefined") { + nBytes = this.defBytes; + } + + const words = Math.floor((nBytes -1)/4)+1; + let p = pos; + + const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); + + for (let i=0; i>2] = rd.remainder.toJSNumber(); + v = rd.quotient; + p += 4; + } + if (!v.isZero()) { + throw new Error('Expected v to be 0'); + } +/* this.i32[p>>2] = bigInt(nums[i]).shiftRight( (words-1)*this.bitsPerBytes).toJSNumber(); + p += 4; +*/ } + + return pos; + } + + get(pos, nElements, nBytes) { + if (typeof nBytes == "undefined") { + if (typeof nElements == "undefined") { + nElements = 1; + nBytes = this.defBytes; + } else { + nElements = nBytes; + nBytes = this.defBytes; + } + } + + const words = Math.floor((nBytes -1)/4)+1; + + const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); + + + const nums = []; + for (let i=0; i=0; j--) { + acc = acc.times(CHUNK); + let v = this.i32[(pos>>2)+j]; + if (this.bitsPerBytes <32) { + if (v&0x80000000) v = v-0x100000000; + } + acc = acc.add(v); + } + nums.push(acc); + pos += words*4; + } + + if (nums.length == 1) return nums[0]; + return nums; + } +} + +module.exports = buildProtoboard; + + +/***/ }), + +/***/ 60484: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const bigInt = __webpack_require__(92096); + +function toNumber(n) { + let v; + if (typeof n=="string") { + if (n.slice(0,2).toLowerCase() == "0x") { + v = bigInt(n.slice(2),16); + } else { + v = bigInt(n); + } + } else { + v = bigInt(n); + } + return v; +} + +function u32(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + return b; +} + +function u64(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + b.push(v.shiftRight(32).and(0xFF).toJSNumber()); + b.push(v.shiftRight(40).and(0xFF).toJSNumber()); + b.push(v.shiftRight(48).and(0xFF).toJSNumber()); + b.push(v.shiftRight(56).and(0xFF).toJSNumber()); + return b; +} + +function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; +} + +function string(str) { + const bytes = toUTF8Array(str); + return [ ...varuint32(bytes.length), ...bytes ]; +} + +function varuint(n) { + const code = []; + let v = toNumber(n); + if (v.isNegative()) throw new Error("Number cannot be negative"); + while (!v.isZero()) { + code.push(v.and(0x7F).toJSNumber()); + v = v.shiftRight(7); + } + if (code.length==0) code.push(0); + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + + +// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); +// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); +// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); + +module.exports.buildBn128 = __webpack_require__(23584); +module.exports.buildBls12381 = __webpack_require__(26920); +// module.exports.buildMnt6753 = require("./src/mnt6753/build_mnt7.js"); + + +/***/ }), + +/***/ 26920: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const bigInt = __webpack_require__(92096); +const utils = __webpack_require__(12333); + +const buildF1m =__webpack_require__(70075); +const buildF1 =__webpack_require__(38138); +const buildF2m =__webpack_require__(15420); +const buildF3m =__webpack_require__(77173); +const buildCurve =__webpack_require__(15904); +const buildFFT = __webpack_require__(93911); +const buildPol = __webpack_require__(2896); +const buildQAP = __webpack_require__(10637); +const buildApplyKey = __webpack_require__(23320); + +// Definition here: https://electriccoin.co/blog/new-snark-curve/ + +module.exports = function buildBLS12381(module, _prefix) { + + const prefix = _prefix || "bls12381"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = bigInt("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); + const r = bigInt("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); + + const n64q = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8q = n64q*8; + const f1size = n8q; + const f2size = f1size * 2; + const f6size = f1size * 6; + const ftsize = f1size * 12; + + const n64r = Math.floor((r.minus(1).bitLength() - 1)/64) +1; + const n8r = n64r*8; + const frsize = n8r; + + + const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m(module, q, "f1m", "intq"); + buildF1(module, r, "fr", "frm", "intr"); + const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(4)), f1size )); + const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); + + buildFFT(module, "frm", "frm", "frm", "frm_mul"); + + buildPol(module, "pol", "frm"); + buildQAP(module, "qap", "frm"); + + const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ) + ]); + const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8r)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8r), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8r, n8r, n8r, "frm_mul"); + buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8q*3, n8q*3, n8r, "g1m_timesFr"); + buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8q*2, n8q*3, n8r, "g1m_timesFrAffine"); + buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8q*2*3, n8q*3*2, n8r, "g2m_timesFr"); + buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8q*2*2, n8q*3*2, n8r, "g2m_timesFrAffine"); + + + function toMontgomery(a) { + return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); + } + + const G1gen = [ + bigInt("3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507"), + bigInt("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569"), + bigInt.one + ]; + + const pG1gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + bigInt.zero, + bigInt.one, + bigInt.zero + ]; + + const pG1zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + bigInt("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), + bigInt("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758"), + ],[ + bigInt("1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905"), + bigInt("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582"), + ],[ + bigInt.one, + bigInt.zero, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + bigInt.zero, + bigInt.zero, + ],[ + bigInt.one, + bigInt.zero, + ],[ + bigInt.zero, + bigInt.zero, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), + ...utils.bigInt2BytesLE( bigInt(0), f1size ) + ]); + + const pBls12381Twist = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwistCoefB = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), + ]); + + function build_mulNR2() { + const f = module.addFunction(f2mPrefix + "_mulNR"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x0c = c.i32_const(module.alloc(f1size)); + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1size)); + const r0 = c.getLocal("pr"); + const r1 = c.i32_add(c.getLocal("pr"), c.i32_const(f1size)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, x0c), + c.call(f1mPrefix+"_sub", x0, x1, r0), + c.call(f1mPrefix+"_add", x0c, x1, r1), + ); + } + build_mulNR2(); + + const f6mPrefix = buildF3m(module, f2mPrefix+"_mulNR", "f6m", "f2m"); + + function build_mulNR6() { + const f = module.addFunction(f6mPrefix + "_mulNR"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const c0copy = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c0copy + ), + c.call( + f2mPrefix + "_mulNR", + c.i32_add(c.getLocal("x"), c.i32_const(n8q*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8q*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8q*4)), + ), + c.call( + f2mPrefix + "_copy", + c0copy, + c.i32_add(c.getLocal("pr"), c.i32_const(n8q*2)), + ), + ); + } + build_mulNR6(); + + const ftmPrefix = buildF2m(module, f6mPrefix+"_mulNR", "ftm", f6mPrefix); + + const ateLoopCount = bigInt("d201000000010000", 16); + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + const isLoopNegative = true; + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8q; + const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = true; + + const finalExpZ = bigInt("15132376222941642752"); + + + module.modules[prefix] = { + n64q: n64q, + n64r: n64r, + n8q: n8q, + n8r: n8r, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + r: r, + q: q, + prePSize: prePSize, + preQSize: preQSize + }; + + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("R", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const t0 = c.getLocal("r"); + const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + + const zsquared = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // tmp0 = r.x.square(); + c.call(f2mPrefix + "_square", Rx, t0), + + // tmp1 = r.y.square(); + c.call(f2mPrefix + "_square", Ry, t1), + + // tmp2 = tmp1.square(); + c.call(f2mPrefix + "_square", t1, t2), + + // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; + c.call(f2mPrefix + "_add", t1, Rx, t3), + c.call(f2mPrefix + "_square", t3, t3), + c.call(f2mPrefix + "_sub", t3, t0, t3), + c.call(f2mPrefix + "_sub", t3, t2, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp4 = tmp0 + tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t4), + c.call(f2mPrefix + "_add", t4, t0, t4), + + // tmp6 = r.x + tmp4; + c.call(f2mPrefix + "_add", Rx, t4, t6), + + // tmp5 = tmp4.square(); + c.call(f2mPrefix + "_square", t4, t5), + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // r.x = tmp5 - tmp3 - tmp3; + c.call(f2mPrefix + "_sub", t5, t3, Rx), + c.call(f2mPrefix + "_sub", Rx, t3, Rx), + + // r.z = (r.z + r.y).square() - tmp1 - zsquared; + c.call(f2mPrefix + "_add", Rz, Ry, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, t1, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + + // r.y = (tmp3 - r.x) * tmp4; + c.call(f2mPrefix + "_sub", t3, Rx, Ry), + c.call(f2mPrefix + "_mul", Ry, t4, Ry), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // r.y -= tmp2; + c.call(f2mPrefix + "_sub", Ry, t2, Ry), + + // tmp3 = tmp4 * zsquared; + c.call(f2mPrefix + "_mul", t4, zsquared, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp3 = -tmp3; + c.call(f2mPrefix + "_neg", t3, t3), + + // tmp6 = tmp6.square() - tmp0 - tmp5; + c.call(f2mPrefix + "_square", t6, t6), + c.call(f2mPrefix + "_sub", t6, t0, t6), + c.call(f2mPrefix + "_sub", t6, t5, t6), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp6 = tmp6 - tmp1; + c.call(f2mPrefix + "_sub", t6, t1, t6), + + // tmp0 = r.z * zsquared; + c.call(f2mPrefix + "_mul", Rz, zsquared, t0), + + // tmp0 = tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("R", "i32"); + f.addParam("Q", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const Qx = c.getLocal("Q"); + const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); + + const t10 = c.getLocal("r"); + const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + const zsquared = c.i32_const(module.alloc(f2size)); + const ysquared = c.i32_const(module.alloc(f2size)); + const ztsquared = c.i32_const(module.alloc(f2size)); + const t0 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const t6 = c.i32_const(module.alloc(f2size)); + const t7 = c.i32_const(module.alloc(f2size)); + const t8 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // ysquared = q.y.square(); + c.call(f2mPrefix + "_square", Qy, ysquared), + + // t0 = zsquared * q.x; + c.call(f2mPrefix + "_mul", zsquared, Qx, t0), + + // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; + c.call(f2mPrefix + "_add", Qy, Rz, t1), + c.call(f2mPrefix + "_square", t1, t1), + c.call(f2mPrefix + "_sub", t1, ysquared, t1), + c.call(f2mPrefix + "_sub", t1, zsquared, t1), + c.call(f2mPrefix + "_mul", t1, zsquared, t1), + + // t2 = t0 - r.x; + c.call(f2mPrefix + "_sub", t0, Rx, t2), + + // t3 = t2.square(); + c.call(f2mPrefix + "_square", t2, t3), + + // t4 = t3 + t3; + c.call(f2mPrefix + "_add", t3, t3, t4), + + // t4 = t4 + t4; + c.call(f2mPrefix + "_add", t4, t4, t4), + + // t5 = t4 * t2; + c.call(f2mPrefix + "_mul", t4, t2, t5), + + // t6 = t1 - r.y - r.y; + c.call(f2mPrefix + "_sub", t1, Ry, t6), + c.call(f2mPrefix + "_sub", t6, Ry, t6), + + // t9 = t6 * q.x; + c.call(f2mPrefix + "_mul", t6, Qx, t9), + + // t7 = t4 * r.x; + c.call(f2mPrefix + "_mul", t4, Rx, t7), + + // r.x = t6.square() - t5 - t7 - t7; + c.call(f2mPrefix + "_square", t6, Rx), + c.call(f2mPrefix + "_sub", Rx, t5, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + + // r.z = (r.z + t2).square() - zsquared - t3; + c.call(f2mPrefix + "_add", Rz, t2, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + c.call(f2mPrefix + "_sub", Rz, t3, Rz), + + // t10 = q.y + r.z; + c.call(f2mPrefix + "_add", Qy, Rz, t10), + + // t8 = (t7 - r.x) * t6; + c.call(f2mPrefix + "_sub", t7, Rx, t8), + c.call(f2mPrefix + "_mul", t8, t6, t8), + + // t0 = r.y * t5; + c.call(f2mPrefix + "_mul", Ry, t5, t0), + + // t0 = t0 + t0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + // r.y = t8 - t0; + c.call(f2mPrefix + "_sub", t8, t0, Ry), + + // t10 = t10.square() - ysquared; + c.call(f2mPrefix + "_square", t10, t10), + c.call(f2mPrefix + "_sub", t10, ysquared, t10), + + // ztsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, ztsquared), + + // t10 = t10 - ztsquared; + c.call(f2mPrefix + "_sub", t10, ztsquared, t10), + + // t9 = t9 + t9 - t10; + c.call(f2mPrefix + "_add", t9, t9, t9), + c.call(f2mPrefix + "_sub", t9, t10, t9), + + // t10 = r.z + r.z; + c.call(f2mPrefix + "_add", Rz, Rz, t10), + + // t6 = -t6; + c.call(f2mPrefix + "_neg", t6, t6), + + // t1 = t6 + t6; + c.call(f2mPrefix + "_add", t6, t6, t1), + ); + } + + + function buildPrepareG2() { + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + + const Q = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + + const base = c.getLocal("ppreQ"); + + f.addCode( + c.call(g2mPrefix + "_normalize", Q, base), + c.if( + c.call(g2mPrefix + "_isZero", base), + c.ret([]) + ), + c.call(g2mPrefix + "_copy", base, R), + c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), + ); + + f.addCode( + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildF6Mul1() { + const f = module.addFunction(f6mPrefix+ "_mul1"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue(); + c.call(f2mPrefix + "_mulNR", t1, t1), + + // let t2 = (self.c0 + self.c1) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + ); + } + buildF6Mul1(); + + function buildF6Mul01() { + const f = module.addFunction(f6mPrefix+ "_mul01"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const a_a = c.i32_const(module.alloc(f1size*2)); + const b_b = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + // let a_a = self.c0 * c0; + c.call(f2mPrefix + "_mul", A_c0, c0, a_a), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_add", A_c1, A_c2, t1), + c.call(f2mPrefix + "_mul", t1, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue() + a_a; + c.call(f2mPrefix + "_mulNR", t1, t1), + c.call(f2mPrefix + "_add", t1, a_a, t1), + + // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; + c.call(f2mPrefix + "_add", c0, c1, t2), + c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), + c.call(f2mPrefix + "_sub", t2, a_a, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + + // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), + c.call(f2mPrefix + "_sub", t3, a_a, t3), + c.call(f2mPrefix + "_add", t3, b_b, t3), + + + ); + } + buildF6Mul01(); + + + function buildF12Mul014() { + + const f = module.addFunction(ftmPrefix+ "_mul014"); + f.addParam("pA", "i32"); // F12 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pC4", "i32"); // F2 + f.addParam("pR", "i32"); // F12 + + const c = f.getCodeBuilder(); + + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + const c4 = c.getLocal("pC4"); + + const aa = c.i32_const(module.alloc(f1size*6)); + const bb = c.i32_const(module.alloc(f1size*6)); + const o = c.i32_const(module.alloc(f1size*2)); + + const R_c0 = c.getLocal("pR"); + const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); + + f.addCode( + // let aa = self.c0.mul_by_01(c0, c1); + c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), + + // let bb = self.c1.mul_by_1(c4); + c.call(f6mPrefix + "_mul1", A_c1, c4, bb), + + // let o = c1 + c4; + c.call(f2mPrefix + "_add", c1, c4, o), + + // let c1 = self.c1 + self.c0; + c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), + + // let c1 = c1.mul_by_01(c0, &o); + c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), + + // let c1 = c1 - aa - bb; + c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), + c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), + + // let c0 = bb; + c.call(f6mPrefix + "_copy", bb, R_c0), + + // let c0 = c0.mul_by_nonresidue(); + c.call(f6mPrefix + "_mulNR", R_c0, R_c0), + + // let c0 = c0 + aa; + c.call(f6mPrefix + "_add", R_c0, aa, R_c0), + ); + } + buildF12Mul014(); + + + function buildELL() { + const f = module.addFunction(prefix+ "_ell"); + f.addParam("pP", "i32"); + f.addParam("pCoefs", "i32"); + f.addParam("pF", "i32"); + + const c = f.getCodeBuilder(); + + const Px = c.getLocal("pP"); + const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); + + const F = c.getLocal("pF"); + + const coef0_0 = c.getLocal("pCoefs"); + const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); + const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); + const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); + const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); + + const pc0 = module.alloc(f1size*2); + const c0 = c.i32_const(pc0); + const c0_c0 = c.i32_const(pc0); + const c0_c1 = c.i32_const(pc0+f1size); + + const pc1 = module.alloc(f1size*2); + const c1 = c.i32_const(pc1); + const c1_c0 = c.i32_const(pc1); + const c1_c1 = c.i32_const(pc1+f1size); + f.addCode( + // let mut c0 = coeffs.0; + // let mut c1 = coeffs.1; + // + // c0.c0 *= p.y; + // c0.c1 *= p.y; + // + // c1.c0 *= p.x; + // c1.c1 *= p.x; + // + // f.mul_by_014(&coeffs.2, &c1, &c0) + + c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), + c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), + c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), + c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), + + c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), + + ); + + } + buildELL(); + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP = c.getLocal("ppreP"); + const preQ = c.getLocal("ppreQ"); + + const coefs = c.getLocal("pCoef"); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.if( + c.call(g1mPrefix + "_isZero", preP), + c.ret([]) + ), + c.if( + c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), + c.ret([]) + ), + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(prefix + "_ell", preP, coefs, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_ell", preP, coefs, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.call(ftmPrefix + "_square", F, F), + + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + c.call(prefix + "_ell", preP, coefs, F), + + ); + + + if (isLoopNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", F, F), + ); + } + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], + [bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], + [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], + [bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], + [bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], + ] + ]; + + const F6 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("0"), bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("0"), bigInt("1")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("0"), bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], + ] + ]; + + const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils.bigInt2BytesLE(toMontgomery(coef[0]), n8q), + ...utils.bigInt2BytesLE(toMontgomery(coef[1]), n8q), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt(a[0]); + const ac1 = bigInt(a[1]); + const bc0 = bigInt(b[0]); + const bc1 = bigInt(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mulNR", x1, t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mulNR", x3, t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mulNR", x5, t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, isExpNegative, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + if (isExpNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", res, res), + ); + } + + } + + function buildFinalExponentiation() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); + + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const res = c.getLocal("r"); + const t0 = c.i32_const(module.alloc(ftsize)); + const t1 = c.i32_const(module.alloc(ftsize)); + const t2 = c.i32_const(module.alloc(ftsize)); + const t3 = c.i32_const(module.alloc(ftsize)); + const t4 = c.i32_const(module.alloc(ftsize)); + const t5 = c.i32_const(module.alloc(ftsize)); + const t6 = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + // let mut t0 = f.frobenius_map(6) + c.call(ftmPrefix + "_frobeniusMap6", elt, t0), + + // let t1 = f.invert() + c.call(ftmPrefix + "_inverse", elt, t1), + + // let mut t2 = t0 * t1; + c.call(ftmPrefix + "_mul", t0, t1, t2), + + // t1 = t2.clone(); + c.call(ftmPrefix + "_copy", t2, t1), + + // t2 = t2.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t2, t2), + + // t2 *= t1; + c.call(ftmPrefix + "_mul", t2, t1, t2), + + + // t1 = cyclotomic_square(t2).conjugate(); + c.call(prefix + "__cyclotomicSquare", t2, t1), + c.call(ftmPrefix + "_conjugate", t1, t1), + + // let mut t3 = cycolotomic_exp(t2); + c.call(prefix + "__cyclotomicExp_w0", t2, t3), + + // let mut t4 = cyclotomic_square(t3); + c.call(prefix + "__cyclotomicSquare", t3, t4), + + // let mut t5 = t1 * t3; + c.call(ftmPrefix + "_mul", t1, t3, t5), + + // t1 = cycolotomic_exp(t5); + c.call(prefix + "__cyclotomicExp_w0", t5, t1), + + // t0 = cycolotomic_exp(t1); + c.call(prefix + "__cyclotomicExp_w0", t1, t0), + + // let mut t6 = cycolotomic_exp(t0); + c.call(prefix + "__cyclotomicExp_w0", t0, t6), + + // t6 *= t4; + c.call(ftmPrefix + "_mul", t6, t4, t6), + + // t4 = cycolotomic_exp(t6); + c.call(prefix + "__cyclotomicExp_w0", t6, t4), + + // t5 = t5.conjugate(); + c.call(ftmPrefix + "_conjugate", t5, t5), + + // t4 *= t5 * t2; + c.call(ftmPrefix + "_mul", t4, t5, t4), + c.call(ftmPrefix + "_mul", t4, t2, t4), + + // t5 = t2.conjugate(); + c.call(ftmPrefix + "_conjugate", t2, t5), + + // t1 *= t2; + c.call(ftmPrefix + "_mul", t1, t2, t1), + + // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap3", t1, t1), + + // t6 *= t5; + c.call(ftmPrefix + "_mul", t6, t5, t6), + + // t6 = t6.frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap1", t6, t6), + + // t3 *= t0; + c.call(ftmPrefix + "_mul", t3, t0, t3), + + // t3 = t3.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t3, t3), + + // t3 *= t1; + c.call(ftmPrefix + "_mul", t3, t1, t3), + + // t3 *= t6; + c.call(ftmPrefix + "_mul", t3, t6, t3), + + // f = t3 * t4; + c.call(ftmPrefix + "_mul", t3, t4, res), + + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); + + const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 544 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), + ); + } + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i { + +const bigInt = __webpack_require__(92096); +const utils = __webpack_require__(12333); + +const buildF1m =__webpack_require__(70075); +const buildF1 =__webpack_require__(38138); +const buildF2m =__webpack_require__(15420); +const buildF3m =__webpack_require__(77173); +const buildCurve =__webpack_require__(15904); +const buildFFT = __webpack_require__(93911); +const buildPol = __webpack_require__(2896); +const buildQAP = __webpack_require__(10637); +const buildApplyKey = __webpack_require__(23320); + +module.exports = function buildBN128(module, _prefix) { + + const prefix = _prefix || "bn128"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"); + const r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + + + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + const frsize = n8; + const f1size = n8; + const f2size = f1size * 2; + const f6size = f1size * 6; + const ftsize = f1size * 12; + + const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m(module, q, "f1m"); + buildF1(module, r, "fr", "frm"); + + const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(3)), f1size )); + const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); + + buildFFT(module, "frm", "frm", "frm", "frm_mul"); + + buildPol(module, "pol", "frm"); + buildQAP(module, "qap", "frm"); + + const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(bigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(bigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) + ]); + const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); + buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); + buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); + buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); + buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); + + function toMontgomery(a) { + return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); + } + + const G1gen = [ + bigInt("1"), + bigInt("2"), + bigInt.one + ]; + + const pG1gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + bigInt.zero, + bigInt.one, + bigInt.zero + ]; + + const pG1zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + bigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"), + bigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634"), + ],[ + bigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"), + bigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531"), + ],[ + bigInt.one, + bigInt.zero, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + bigInt.zero, + bigInt.zero, + ],[ + bigInt.one, + bigInt.zero, + ],[ + bigInt.zero, + bigInt.zero, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pNonResidueF6 = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(9), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), + ...utils.bigInt2BytesLE( bigInt(0), f1size ) + ]); + + const pAltBn128Twist = pNonResidueF6; + + const pTwistCoefB = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), + ]); + + function build_mulNR6() { + const f = module.addFunction(prefix + "_mulNR6"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.getLocal("x"), + c.getLocal("pr") + ) + ); + } + build_mulNR6(); + + const f6mPrefix = buildF3m(module, prefix+"_mulNR6", "f6m", "f2m"); + + function build_mulNR12() { + const f = module.addFunction(prefix + "_mulNR12"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), + ) + ); + } + build_mulNR12(); + + const ftmPrefix = buildF2m(module, prefix+"_mulNR12", "ftm", f6mPrefix); + + + const ateLoopCount = bigInt("29793968203157093288"); + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + const isLoopNegative = false; + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8; + const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = false; + + + module.modules[prefix] = { + n64: n64, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + prePSize: prePSize, + preQSize: preQSize, + r: r.toString(), + q: q.toString() + }; + + // console.log("PrePSize: " +prePSize); + // console.log("PreQSize: " +preQSize); + + const finalExpZ = bigInt("4965661367192848881"); + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("pQ", "i32"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X2 = c.getLocal("pQ"); + const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const D = ELL_VW; + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + // D = X1 - X2*Z1 + c.call(f2mPrefix + "_mul", X2, Z1, D), + c.call(f2mPrefix + "_sub", X1, D, D), + + // E = Y1 - Y2*Z1 + c.call(f2mPrefix + "_mul", Y2, Z1, E), + c.call(f2mPrefix + "_sub", Y1, E, E), + + // F = D^2 + c.call(f2mPrefix + "_square", D, F), + + // G = E^2 + c.call(f2mPrefix + "_square", E, G), + + // H = D*F + c.call(f2mPrefix + "_mul", D, F, H), + + // I = X1 * F + c.call(f2mPrefix + "_mul", X1, F, I), + + // J = H + Z1*G - (I+I) + c.call(f2mPrefix + "_add", I, I, AUX), + c.call(f2mPrefix + "_mul", Z1, G, J), + c.call(f2mPrefix + "_add", H, J, J), + c.call(f2mPrefix + "_sub", J, AUX, J), + + + // X3 (X1) = D*J + c.call(f2mPrefix + "_mul", D, J, X1), + + // Y3 (Y1) = E*(I-J)-(H*Y1) + c.call(f2mPrefix + "_mul", H, Y1, Y1), + c.call(f2mPrefix + "_sub", I, J, AUX), + c.call(f2mPrefix + "_mul", E, AUX, AUX), + c.call(f2mPrefix + "_sub", AUX, Y1, Y1), + + // Z3 (Z1) = Z1*H + c.call(f2mPrefix + "_mul", Z1, H, Z1), + + // ell_0 = xi * (E * X2 - D * Y2) + c.call(f2mPrefix + "_mul", D, Y2, AUX), + c.call(f2mPrefix + "_mul", E, X2, ELL_0), + c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), + c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), + + + // ell_VV = - E (later: * xP) + c.call(f2mPrefix + "_neg", E, ELL_VV), + + // ell_VW = D (later: * yP ) + // Already assigned + + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const A = c.i32_const(module.alloc(f2size)); + const B = c.i32_const(module.alloc(f2size)); + const C = c.i32_const(module.alloc(f2size)); + const D = c.i32_const(module.alloc(f2size)); + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const E2 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // A = X1 * Y1 / 2 + c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), + c.call(f2mPrefix + "_mul", X1, A, A), + + // B = Y1^2 + c.call(f2mPrefix + "_square", Y1, B), + + // C = Z1^2 + c.call(f2mPrefix + "_square", Z1, C), + + // D = 3 * C + c.call(f2mPrefix + "_add", C, C, D), + c.call(f2mPrefix + "_add", D, C, D), + + // E = twist_b * D + c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), + + // F = 3 * E + c.call(f2mPrefix + "_add", E, E, F), + c.call(f2mPrefix + "_add", E, F, F), + + // G = (B+F)/2 + c.call(f2mPrefix + "_add", B, F, G), + c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), + + // H = (Y1+Z1)^2-(B+C) + c.call(f2mPrefix + "_add", B, C, AUX), + c.call(f2mPrefix + "_add", Y1, Z1, H), + c.call(f2mPrefix + "_square", H, H), + c.call(f2mPrefix + "_sub", H, AUX, H), + + // I = E-B + c.call(f2mPrefix + "_sub", E, B, I), + + // J = X1^2 + c.call(f2mPrefix + "_square", X1, J), + + // E_squared = E^2 + c.call(f2mPrefix + "_square", E, E2), + + // X3 (X1) = A * (B-F) + c.call(f2mPrefix + "_sub", B, F, AUX), + c.call(f2mPrefix + "_mul", A, AUX, X1), + + // Y3 (Y1) = G^2 - 3*E^2 + c.call(f2mPrefix + "_add", E2, E2, AUX), + c.call(f2mPrefix + "_add", E2, AUX, AUX), + c.call(f2mPrefix + "_square", G, Y1), + c.call(f2mPrefix + "_sub", Y1, AUX, Y1), + + // Z3 (Z1) = B * H + c.call(f2mPrefix + "_mul", B, H, Z1), + + // ell_0 = xi * I + c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), + + // ell_VW = - H (later: * yP) + c.call(f2mPrefix + "_neg", H, ELL_VW), + + // ell_VV = 3*J (later: * xP) + c.call(f2mPrefix + "_add", J, J, ELL_VV), + c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), + + ); + } + + function buildMulByQ() { + const f = module.addFunction(prefix + "_mulByQ"); + f.addParam("p1", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("p1"); + const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); + const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); + const x3 = c.getLocal("pr"); + const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); + const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); + + const MulByQX = c.i32_const(module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), + ])); + + const MulByQY = c.i32_const(module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), + ])); + + f.addCode( + // The frobeniusMap(1) in this field, is the conjugate + c.call(f2mPrefix + "_conjugate", x, x3), + c.call(f2mPrefix + "_mul", MulByQX, x3, x3), + c.call(f2mPrefix + "_conjugate", y, y3), + c.call(f2mPrefix + "_mul", MulByQY, y3, y3), + c.call(f2mPrefix + "_conjugate", z, z3), + ); + } + + + function buildPrepareG2() { + buildMulByQ(); + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const QX = c.getLocal("pQ"); + const QY = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); + const QZ = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + const RX = c.i32_const(pR); + const RY = c.i32_const(pR+f2size); + const RZ = c.i32_const(pR+2*f2size); + + const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); + const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); + const cQZ = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); + + const pQ1 = module.alloc(f2size*3); + const Q1 = c.i32_const(pQ1); + + const pQ2 = module.alloc(f2size*3); + const Q2 = c.i32_const(pQ2); + const Q2X = c.i32_const(pQ2); + const Q2Y = c.i32_const(pQ2 + f2size); + const Q2Z = c.i32_const(pQ2 + f2size*2); + + f.addCode( + c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine + c.call(f2mPrefix + "_copy", cQX, RX), + c.call(f2mPrefix + "_copy", cQY, RY), + c.call(f2mPrefix + "_one", RZ), + ); + + f.addCode( + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + f.addCode( + c.call(prefix + "_mulByQ", cQX, Q1), + c.call(prefix + "_mulByQ", Q1, Q2) + ); + + if (isLoopNegative) { + f.addCode( + c.call(f2mPrefix + "_neg", RY, RY), + ); + } + + f.addCode( + c.call(f2mPrefix + "_neg", Q2Y, Q2Y), + + c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ); + } + + function buildMulBy024Old() { + const f = module.addFunction(prefix+ "__mulBy024Old"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + + const pAUX12 = module.alloc(ftsize); + const AUX12 = c.i32_const(pAUX12); + const AUX12_0 = c.i32_const(pAUX12); + const AUX12_2 = c.i32_const(pAUX12+f2size); + const AUX12_4 = c.i32_const(pAUX12+f2size*2); + const AUX12_6 = c.i32_const(pAUX12+f2size*3); + const AUX12_8 = c.i32_const(pAUX12+f2size*4); + const AUX12_10 = c.i32_const(pAUX12+f2size*5); + + f.addCode( + + c.call(f2mPrefix + "_copy", x0, AUX12_0), + c.call(f2mPrefix + "_zero", AUX12_2), + c.call(f2mPrefix + "_copy", x2, AUX12_4), + c.call(f2mPrefix + "_zero", AUX12_6), + c.call(f2mPrefix + "_copy", x4, AUX12_8), + c.call(f2mPrefix + "_zero", AUX12_10), + c.call(ftmPrefix + "_mul", AUX12, z0, z0), + ); + } + + function buildMulBy024() { + const f = module.addFunction(prefix+ "__mulBy024"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); + const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); + const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); + const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); + const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const s0 = c.i32_const(module.alloc(f2size)); + const T3 = c.i32_const(module.alloc(f2size)); + const T4 = c.i32_const(module.alloc(f2size)); + const D0 = c.i32_const(module.alloc(f2size)); + const D2 = c.i32_const(module.alloc(f2size)); + const D4 = c.i32_const(module.alloc(f2size)); + const S1 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // D0 = z0 * x0; + c.call(f2mPrefix + "_mul", z0, x0, D0), + // D2 = z2 * x2; + c.call(f2mPrefix + "_mul", z2, x2, D2), + // D4 = z4 * x4; + c.call(f2mPrefix + "_mul", z4, x4, D4), + // t2 = z0 + z4; + c.call(f2mPrefix + "_add", z0, z4, t2), + // t1 = z0 + z2; + c.call(f2mPrefix + "_add", z0, z2, t1), + // s0 = z1 + z3 + z5; + c.call(f2mPrefix + "_add", z1, z3, s0), + c.call(f2mPrefix + "_add", s0, z5, s0), + + + // For z.a_.a_ = z0. + // S1 = z1 * x2; + c.call(f2mPrefix + "_mul", z1, x2, S1), + // T3 = S1 + D4; + c.call(f2mPrefix + "_add", S1, D4, T3), + // T4 = my_Fp6::non_residue * T3 + D0; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + c.call(f2mPrefix + "_add", T4, D0, z0), + // z0 = T4; + + // For z.a_.b_ = z1 + // T3 = z5 * x4; + c.call(f2mPrefix + "_mul", z5, x4, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T3 = T3 + D2; + c.call(f2mPrefix + "_add", T3, D2, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z1 * x0; + c.call(f2mPrefix + "_mul", z1, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z1), + // z1 = T4; + + + + // For z.a_.c_ = z2 + // t0 = x0 + x2; + c.call(f2mPrefix + "_add", x0, x2, t0), + // T3 = t1 * t0 - D0 - D2; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D0, D2, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = z3 * x4; + c.call(f2mPrefix + "_mul", z3, x4, T4), + // S1 = S1 + T4; + c.call(f2mPrefix + "_add", S1, T4, S1), + + + // For z.b_.a_ = z3 (z3 needs z2) + // t0 = z2 + z4; + c.call(f2mPrefix + "_add", z2, z4, t0), + // T3 = T3 + T4; + // z2 = T3; + c.call(f2mPrefix + "_add", T3, T4, z2), + // t1 = x2 + x4; + c.call(f2mPrefix + "_add", x2, x4, t1), + // T3 = t0 * t1 - D2 - D4; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D2, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z3 * x0; + c.call(f2mPrefix + "_mul", z3, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z3), + // z3 = T4; + + // For z.b_.b_ = z4 + // T3 = z5 * x2; + c.call(f2mPrefix + "_mul", z5, x2, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // t0 = x0 + x4; + c.call(f2mPrefix + "_add", x0, x4, t0), + // T3 = t2 * t0 - D0 - D4; + c.call(f2mPrefix + "_mul", t2, t0, T3), + c.call(f2mPrefix + "_add", D0, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z4), + // z4 = T4; + + // For z.b_.c_ = z5. + // t0 = x0 + x2 + x4; + c.call(f2mPrefix + "_add", x0, x2, t0), + c.call(f2mPrefix + "_add", t0, x4, t0), + // T3 = s0 * t0 - S1; + c.call(f2mPrefix + "_mul", s0, t0, T3), + c.call(f2mPrefix + "_sub", T3, S1, z5), + // z5 = T3; + + ); + } + + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP_PX = c.getLocal("ppreP"); + const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + + const pVW = module.alloc(f2size); + const VW = c.i32_const(pVW); + const pVV = module.alloc(f2size); + const VV = c.i32_const(pVV); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(ftmPrefix + "_square", F, F), + + c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + + ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + + ); + + if (isLoopNegative) { + f.addCode( + c.call(ftmPrefix + "_inverse", F, F), + ); + } + + f.addCode( + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ); + + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt("16469823323077808223889137241176536799009286646108169935659301613961712198316")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt("0")], + [bigInt("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt("303847389135065887422783454877609941456349188919719272345083954437860409601")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt("5722266937896532885780051958958348231143373700109372999374820235121374419868")], + [bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt("0")], + [bigInt("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt("5418419548761466998357268504080738289687024511189653727029736280683514010267")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt("21584395482704209334823622290379665147239961968378104390343953940207365798982")], + [bigInt("2203960485148121921418603742825762020974279258880205651967"), bigInt("0")], + [bigInt("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt("16165975933942742336466353786298926857552937457188450663314217659523851788715")], + ] + ]; + + const F6 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt("10307601595873709700152284273816112264069230130616436755625194854815875713954")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt("2236595495967245188281701248203181795121068902605861227855261137820944008926")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt("9344045779998320333812420223237981029506012124075525679208581902008406485703")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt("19937756971775647987995932169929341994314640652964949448313374472400716661030")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt("16208900380737693084919495127334387981393726419856888799917914180988844123039")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt("7629828391165209371577384193250820201684255241773809077146787135900891633097")], + ] + ]; + + const f = module.addFunction(prefix+ "__frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils.bigInt2BytesLE(toMontgomery(coef[0]), 32), + ...utils.bigInt2BytesLE(toMontgomery(coef[1]), 32), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt(a[0]); + const ac1 = bigInt(a[1]); + const bc0 = bigInt(b[0]); + const bc1 = bigInt(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + + function buildFinalExponentiationFirstChunk() { + + const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const eltC0 = elt; + const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); + const r = c.getLocal("r"); + const pA = module.alloc(ftsize); + const A = c.i32_const(pA); + const Ac0 = A; + const Ac1 = c.i32_const(pA + n8*6); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + + f.addCode( + // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); + c.call(f6mPrefix + "_copy", eltC0, Ac0), + c.call(f6mPrefix + "_neg", eltC1, Ac1), + + // const alt_bn128_Fq12 B = elt.inverse(); + c.call(ftmPrefix + "_inverse", elt, B), + + // const alt_bn128_Fq12 C = A * B; + c.call(ftmPrefix + "_mul", A, B, C), + // const alt_bn128_Fq12 D = C.Frobenius_map(2); + c.call(prefix + "__frobeniusMap2", C, D), + // const alt_bn128_Fq12 result = D * C; + c.call(ftmPrefix + "_mul", C, D, r), + ); + } + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, 32)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildFinalExponentiationLastChunk() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, "w0"); + + const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const A = c.i32_const(module.alloc(ftsize)); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + const E = c.i32_const(module.alloc(ftsize)); + const F = c.i32_const(module.alloc(ftsize)); + const G = c.i32_const(module.alloc(ftsize)); + const H = c.i32_const(module.alloc(ftsize)); + const I = c.i32_const(module.alloc(ftsize)); + const J = c.i32_const(module.alloc(ftsize)); + const K = c.i32_const(module.alloc(ftsize)); + const L = c.i32_const(module.alloc(ftsize)); + const M = c.i32_const(module.alloc(ftsize)); + const N = c.i32_const(module.alloc(ftsize)); + const O = c.i32_const(module.alloc(ftsize)); + const P = c.i32_const(module.alloc(ftsize)); + const Q = c.i32_const(module.alloc(ftsize)); + const R = c.i32_const(module.alloc(ftsize)); + const S = c.i32_const(module.alloc(ftsize)); + const T = c.i32_const(module.alloc(ftsize)); + const U = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + + // A = exp_by_neg_z(elt) // = elt^(-z) + c.call(prefix + "__cyclotomicExp_w0", elt, A), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", A, A), + // B = A^2 // = elt^(-2*z) + c.call(prefix + "__cyclotomicSquare", A, B), + // C = B^2 // = elt^(-4*z) + c.call(prefix + "__cyclotomicSquare", B, C), + // D = C * B // = elt^(-6*z) + c.call(ftmPrefix + "_mul", C, B, D), + // E = exp_by_neg_z(D) // = elt^(6*z^2) + c.call(prefix + "__cyclotomicExp_w0", D, E), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", E, E), + // F = E^2 // = elt^(12*z^2) + c.call(prefix + "__cyclotomicSquare", E, F), + // G = epx_by_neg_z(F) // = elt^(-12*z^3) + c.call(prefix + "__cyclotomicExp_w0", F, G), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", G, G), + // H = conj(D) // = elt^(6*z) + c.call(ftmPrefix + "_conjugate", D, H), + // I = conj(G) // = elt^(12*z^3) + c.call(ftmPrefix + "_conjugate", G, I), + // J = I * E // = elt^(12*z^3 + 6*z^2) + c.call(ftmPrefix + "_mul", I, E, J), + // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) + c.call(ftmPrefix + "_mul", J, H, K), + // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) + c.call(ftmPrefix + "_mul", K, B, L), + // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) + c.call(ftmPrefix + "_mul", K, E, M), + + // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) + c.call(ftmPrefix + "_mul", M, elt, N), + + // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) + c.call(prefix + "__frobeniusMap1", L, O), + // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", O, N, P), + // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) + c.call(prefix + "__frobeniusMap2", K, Q), + // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", Q, P, R), + // S = conj(elt) // = elt^(-1) + c.call(ftmPrefix + "_conjugate", elt, S), + // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) + c.call(ftmPrefix + "_mul", S, L, T), + // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) + c.call(prefix + "__frobeniusMap3", T, U), + // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", U, R, result), + // result = V + ); + } + + + function buildFinalExponentiation() { + buildFinalExponentiationFirstChunk(); + buildFinalExponentiationLastChunk(); + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); + + f.addCode( + c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), + c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); + + const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 352 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), + ); + } + + + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i { + + + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { + + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pFirst", "i32"); + f.addParam("pInc", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("pOldFree", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pFrom", "i32"); + f.addLocal("pTo", "i32"); + + const c = f.getCodeBuilder(); + + const t = c.i32_const(module.alloc(sizeF)); + + f.addCode( + c.setLocal("pFrom", c.getLocal("pIn")), + c.setLocal("pTo", c.getLocal("pOut")), + ); + + // t = first + f.addCode( + c.call( + frPrefix + "_copy", + c.getLocal("pFirst"), + t + ) + ); + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call( + opGtimesF, + c.getLocal("pFrom"), + t, + c.getLocal("pTo") + ), + c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), + c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + + // t = t* inc + c.call( + frPrefix + "_mul", + t, + c.getLocal("pInc"), + t + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + module.exportFunction(fnName); + +}; + + +/***/ }), + +/***/ 9440: +/***/ ((module) => { + + + +module.exports = buildBatchConvertion; + +function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } + + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut", "i32"); + + const c = f.getCodeBuilder(); + + if (reverse) { + f.addCode( + c.setLocal("itIn", + c.i32_add( + c.getLocal("pIn"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn", c.getLocal("pIn")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + + +/***/ }), + +/***/ 18163: +/***/ ((module) => { + + +module.exports = buildBatchInverse; + +function buildBatchInverse(module, prefix) { + + + const n8 = module.modules[prefix].n64*8; + + const f = module.addFunction(prefix+"_batchInverse"); + f.addParam("pIn", "i32"); + f.addParam("inStep", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addParam("outStep", "i32"); + f.addLocal("itAux", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut","i32"); + f.addLocal("i","i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + + // Alloc Working space for accumulated umltiplications + f.addCode( + c.setLocal("itAux", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("itAux"), + c.i32_mul( + c.i32_add( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(n8) + ) + ) + ) + ); + + f.addCode( + + // aux[0] = a; + c.call(prefix+"_one", c.getLocal("itAux")), + // for (i=0;i { + + + +module.exports = buildBatchConvertion; + +function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } + + const f = module.addFunction(fnName); + f.addParam("pIn1", "i32"); + f.addParam("pIn2", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn1", "i32"); + f.addLocal("itIn2", "i32"); + f.addLocal("itOut", "i32"); + + const c = f.getCodeBuilder(); + + if (reverse) { + f.addCode( + c.setLocal("itIn1", + c.i32_add( + c.getLocal("pIn1"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itIn2", + c.i32_add( + c.getLocal("pIn2"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn1"), c.getLocal("itIn2"), c.getLocal("itOut")), + + c.setLocal("itIn1", c.i32_sub(c.getLocal("itIn1"), c.i32_const(sizeIn))), + c.setLocal("itIn2", c.i32_sub(c.getLocal("itIn2"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn1", c.getLocal("pIn1")), + c.setLocal("itIn2", c.getLocal("pIn2")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn1"), c.getLocal("itIn2"), c.getLocal("itOut")), + + c.setLocal("itIn1", c.i32_add(c.getLocal("itIn1"), c.i32_const(sizeIn))), + c.setLocal("itIn2", c.i32_add(c.getLocal("itIn2"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + + +/***/ }), + +/***/ 15904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildTimesScalarNAF = __webpack_require__(33972); +//const buildTimesScalar = require("./build_timesscalar"); +const buildBatchConvertion = __webpack_require__(9440); +const buildMultiexp = __webpack_require__(74911); + +module.exports = function buildCurve(module, prefix, prefixField, pB) { + + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64*3 + }; + + function buildIsZero() { + const f = module.addFunction(prefix + "_isZero"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8*2) + ) + )); + } + function buildIsZeroAffine() { + const f = module.addFunction(prefix + "_isZeroAffine"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_and( + c.call( + prefixField + "_isZero", + c.getLocal("p1") + ), + c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8) + ) + ) + ) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix + "_copy"); + f.addParam("ps", "i32"); + f.addParam("pd", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(92096); + +const buildF1m =__webpack_require__(70075); + +module.exports = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { + + const q = bigInt(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + + const prefix = _prefix || "f1"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64 + }; + + const intPrefix = _intPrefix || "int"; + const f1mPrefix = buildF1m(module, q, _f1mPrefix, intPrefix); + + + const pR2 = module.modules[f1mPrefix].pR2; + const pq = module.modules[f1mPrefix].pq; + const pePlusOne = module.modules[f1mPrefix].pePlusOne; + + function buildMul() { + const pAux1 = module.alloc(n8); + + const f = module.addFunction(prefix+ "_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); + f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) + ); + } + + + buildMul(); + buildSquare(); + buildInverse(); + buildIsNegative(); + module.exportFunction(f1mPrefix + "_add", prefix + "_add"); + module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); + module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); + module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); + module.exportFunction(f1mPrefix + "_one", prefix+"_one"); + module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); + + return prefix; +}; + + +/***/ }), + +/***/ 70075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(92096); +const buildInt = __webpack_require__(76754); +const utils = __webpack_require__(12333); +const buildExp = __webpack_require__(50345); +const buildBatchInverse = __webpack_require__(18163); +const buildBatchConvertion = __webpack_require__(9440); +const buildBatchOp = __webpack_require__(4948); + +module.exports = function buildF1m(module, _q, _prefix, _intPrefix) { + const q = bigInt(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n32 = n64*2; + const n8 = n64*8; + + const prefix = _prefix || "f1m"; + if (module.modules[prefix]) return prefix; // already builded + + const intPrefix = buildInt(module, n64, _intPrefix); + const pq = module.alloc(n8, utils.bigInt2BytesLE(q, n8)); + + const pR = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); + const pR2 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).square().mod(q), n8)); + const pOne = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); + const pZero = module.alloc(utils.bigInt2BytesLE(bigInt.zero, n8)); + const _minusOne = q.minus(bigInt.one); + const _e = _minusOne.shiftRight(1); // e = (p-1)/2 + const pe = module.alloc(n8, utils.bigInt2BytesLE(_e, n8)); + + const _ePlusOne = _e.add(bigInt.one); // e = (p-1)/2 + const pePlusOne = module.alloc(n8, utils.bigInt2BytesLE(_ePlusOne, n8)); + + module.modules[prefix] = { + pq: pq, + pR2: pR2, + n64: n64, + q: q, + pOne: pOne, + pZero: pZero, + pePlusOne: pePlusOne + }; + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); + } + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) + ) + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) + ); + } + + +/* + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.i32_and( + c.i32_load(AUX), + c.i32_const(1) + ) + ); + } +*/ + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if ( + c.call(intPrefix + "_isZero", c.getLocal("x")), + c.ret(c.i32_const(0)) + ), + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.if( + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), + c.ret(c.i32_const(-1)) + ), + c.ret(c.i32_const(1)) + ); + } + + + function buildMReduct() { + const carries = module.alloc(n32*n32*8); + + const f = module.addFunction(prefix+"_mReduct"); + f.addParam("t", "i32"); + f.addParam("r", "i32"); + f.addLocal("np32", "i64"); + f.addLocal("c", "i64"); + f.addLocal("m", "i64"); + + const c = f.getCodeBuilder(); + + const np32 = bigInt("100000000",16).minus( q.modInv(bigInt("100000000",16))).toJSNumber(); + + f.addCode(c.setLocal("np32", c.i64_const(np32))); + + for (let i=0; i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + [c0, c1] = [c1, c0]; + f.addCode( + c.setLocal(c1, + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquare() { + + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("c0", "i64"); + f.addLocal("c1", "i64"); + f.addLocal("c0_old", "i64"); + f.addLocal("c1_old", "i64"); + f.addLocal("np32", "i64"); + + + for (let i=0;i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + + for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0_old) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1_old)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildFromMontgomery() { + + const pAux2 = module.alloc(n8*2); + + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); + f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); + f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); + } + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); + f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); + } + + // Calculate various valuse needed for sqrt + + + let _nqr = bigInt(2); + if (q.isPrime()) { + while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt.one); + } + + const pnqr = module.alloc(utils.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); + + let s2 = 0; + let _t = _minusOne; + + while ((!_t.isOdd())&&(!_t.isZero())) { + s2++; + _t = _t.shiftRight(1); + } + const pt = module.alloc(n8, utils.bigInt2BytesLE(_t, n8)); + + const _nqrToT = _nqr.modPow(_t, q); + const pNqrToT = module.alloc(utils.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); + + const _tPlusOneOver2 = _t.add(1).shiftRight(1); + const ptPlusOneOver2 = module.alloc(n8, utils.bigInt2BytesLE(_tPlusOneOver2, n8)); + + function buildSqrt() { + + const f = module.addFunction(prefix+ "_sqrt"); + f.addParam("n", "i32"); + f.addParam("r", "i32"); + f.addLocal("m", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const C = c.i32_const(module.alloc(n8)); + const T = c.i32_const(module.alloc(n8)); + const R = c.i32_const(module.alloc(n8)); + const SQ = c.i32_const(module.alloc(n8)); + const B = c.i32_const(module.alloc(n8)); + + f.addCode( + + // If (n==0) return 0 + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret( + c.call(prefix + "_zero", c.getLocal("r")) + ) + ), + + c.setLocal("m", c.i32_const(s2)), + c.call(prefix + "_copy", c.i32_const(pNqrToT), C), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), + + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", T, ONE)), + + c.call(prefix + "_square", T, SQ), + c.setLocal("i", c.i32_const(1)), + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), + c.call(prefix + "_square", SQ, SQ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_copy", C, B), + c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("j"))), + c.call(prefix + "_square", B, B), + c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("m", c.getLocal("i")), + c.call(prefix + "_square", B, C), + c.call(prefix + "_mul", T, C, T), + c.call(prefix + "_mul", R, B, R), + + c.br(0) + )), + + c.if( + c.call(prefix + "_isNegative", R), + c.call(prefix + "_neg", R, c.getLocal("r")), + c.call(prefix + "_copy", R, c.getLocal("r")), + ) + ); + } + + function buildIsSquare() { + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret(c.i32_const(1)) + ), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), + c.call(prefix + "_eq", AUX, ONE) + ); + } + + + function buildLoad() { + const f = module.addFunction(prefix+"_load"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + f.addLocal("p", "i32"); + f.addLocal("l", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + const c = f.getCodeBuilder(); + + const R = c.i32_const(module.alloc(n8)); + const pAux = module.alloc(n8); + const AUX = c.i32_const(pAux); + + f.addCode( + c.call(intPrefix + "_zero", c.getLocal("r")), + c.setLocal("i", c.i32_const(n8)), + c.setLocal("p", c.getLocal("scalar")), + c.block(c.loop( + c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", c.getLocal("p"), R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), + c.br(0) + )), + + c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), + c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), + c.call(intPrefix + "_zero", AUX), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), + + c.i32_store8( + c.getLocal("j"), + pAux, + c.i32_load8_u(c.getLocal("p")), + ), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", AUX, R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), + c.call(prefix + "_toMontgomery", AUX, AUX), + c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + f.addCode( + c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) + ); + } + + + module.exportFunction(intPrefix + "_copy", prefix+"_copy"); + module.exportFunction(intPrefix + "_zero", prefix+"_zero"); + module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(intPrefix + "_eq", prefix+"_eq"); + + buildIsOne(); + buildAdd(); + buildSub(); + buildNeg(); + buildMReduct(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildToMontgomery(); + buildFromMontgomery(); + buildIsNegative(); + buildSign(); + buildInverse(); + buildOne(); + buildLoad(); + buildTimesScalar(); + buildBatchInverse(module, prefix); + buildBatchConvertion(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); + buildBatchConvertion(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); + buildBatchConvertion(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); + buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); + buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); + buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); + + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_mReduct"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_squareOld"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_load"); + module.exportFunction(prefix + "_timesScalar"); + buildExp( + module, + prefix + "_exp", + n8, + prefix + "_mul", + prefix + "_square", + intPrefix + "_copy", + prefix + "_one", + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_batchInverse"); + if (q.isPrime()) { + buildSqrt(); + buildIsSquare(); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + } + module.exportFunction(prefix + "_batchToMontgomery"); + module.exportFunction(prefix + "_batchFromMontgomery"); + // console.log(module.functionIdxByName); + + return prefix; +}; + + +/***/ }), + +/***/ 15420: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ +const buildExp = __webpack_require__(50345); +const buildBatchInverse = __webpack_require__(18163); +const bigInt = __webpack_require__(92096); +const utils = __webpack_require__(12333); + +module.exports = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + const q = module.modules[f1mPrefix].q; + + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*2 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + function buildConjugate() { + const f = module.addFunction(prefix+"_conjugate"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ); + } + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const A = c.i32_const(module.alloc(f1n8)); + const B = c.i32_const(module.alloc(f1n8)); + const C = c.i32_const(module.alloc(f1n8)); + const D = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 + c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 + + c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 + c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 + c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 + + // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) + c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) + c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) + c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 + c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 + ); + + } + + function buildMul1() { + const f = module.addFunction(prefix+"_mul1"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y = c.getLocal("y"); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y + c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y + ); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const AB = c.i32_const(module.alloc(f1n8)); + const APB = c.i32_const(module.alloc(f1n8)); + const APNB = c.i32_const(module.alloc(f1n8)); + const ABPNAB = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + // AB = x0*y1 + c.call(f1mPrefix + "_mul", x0, x1, AB), + + // APB = x0+y1 + c.call(f1mPrefix + "_add", x0, x1, APB), + + // APBN0 = x0 + nr*x1 + c.call(mulNonResidueFn, x1, APNB), + c.call(f1mPrefix + "_add", x0, APNB, APNB), + + // ABPNAB = ab + nr*ab + c.call(mulNonResidueFn, AB, ABPNAB), + c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), + + // r0 = APB * APNB - ABPNAB + c.call(f1mPrefix + "_mul", APB, APNB, r0), + c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), + + // r1 = AB + AB + c.call(f1mPrefix + "_add", AB, AB, r1), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1) + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), + c.call(mulNonResidueFn, t1, t2), + + c.call(f1mPrefix+"_sub", t0, t2, t2), + c.call(f1mPrefix+"_inverse", t2, t3), + + c.call(f1mPrefix+"_mul", x0, t3, r0), + c.call(f1mPrefix+"_mul", x1, t3, r1), + c.call(f1mPrefix+"_neg", r1, r1), + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.ret(c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1), + )) + ); + } + + + // Check here: https://eprint.iacr.org/2012/685.pdf + // Alg 9adj + function buildSqrt() { + + const f = module.addFunction(prefix+"_sqrt"); + f.addParam("a", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); + const e12 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(1)).divide(2), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + const n1a = c.i32_const(pn1); + const n1b = c.i32_const(pn1+f1n8); + const x0 = c.i32_const(module.alloc(f1n8*2)); + const b = c.i32_const(module.alloc(f1n8*2)); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), + + // const x0 = F.mul(a1, a); + c.call(prefix + "_mul", a1, a, x0), + + // if (F.eq(alfa, F.negone)) { + c.if( + c.call(prefix + "_eq", alpha, n1), + [ + // x = F.mul(x0, [F.F.zero, F.F.one]); + ...c.call(f1mPrefix + "_zero", n1a), + ...c.call(f1mPrefix + "_one", n1b), + ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), + ], + [ + // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); + ...c.call(prefix + "_one", b), + ...c.call(prefix + "_add", b, alpha, b), + ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), + + // x = F.mul(b, x0); + ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), + ] + ) + ); + + } + + + function buildIsSquare() { + + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("a", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if( + c.call( + prefix + "_eq", + a0, + n1 + ), + c.ret(c.i32_const(0)) + ), + c.ret(c.i32_const(1)) + ); + + } + + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildMul1(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildConjugate(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildSign(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_mul1"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_conjugate"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*2, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one", + ); + buildSqrt(); + buildIsSquare(); + + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + module.exportFunction(prefix + "_isNegative"); + + + return prefix; +}; + + +/***/ }), + +/***/ 77173: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ +const buildExp = __webpack_require__(50345); +const buildBatchInverse = __webpack_require__(18163); + +module.exports = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*3 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + c.call(f1mPrefix+"_add", x2, y2, r2), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), + ); + } + + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + c.call(f1mPrefix+"_sub", x2, y2, r2), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + c.call(f1mPrefix+"_neg", x2, r2), + ); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x2), + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x2)) + ); + } + + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const cd = f.getCodeBuilder(); + + const a = cd.getLocal("x"); + const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); + const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); + const A = cd.getLocal("y"); + const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); + const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); + const r0 = cd.getLocal("r"); + const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); + const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); + + const aA = cd.i32_const(module.alloc(f1n8)); + const bB = cd.i32_const(module.alloc(f1n8)); + const cC = cd.i32_const(module.alloc(f1n8)); + const a_b = cd.i32_const(module.alloc(f1n8)); + const A_B = cd.i32_const(module.alloc(f1n8)); + const a_c = cd.i32_const(module.alloc(f1n8)); + const A_C = cd.i32_const(module.alloc(f1n8)); + const b_c = cd.i32_const(module.alloc(f1n8)); + const B_C = cd.i32_const(module.alloc(f1n8)); + const aA_bB = cd.i32_const(module.alloc(f1n8)); + const aA_cC = cd.i32_const(module.alloc(f1n8)); + const bB_cC = cd.i32_const(module.alloc(f1n8)); + const AUX = cd.i32_const(module.alloc(f1n8)); + + + f.addCode( + cd.call(f1mPrefix + "_mul", a, A, aA), + cd.call(f1mPrefix + "_mul", b, B, bB), + cd.call(f1mPrefix + "_mul", c, C, cC), + + cd.call(f1mPrefix + "_add", a, b, a_b), + cd.call(f1mPrefix + "_add", A, B, A_B), + cd.call(f1mPrefix + "_add", a, c, a_c), + cd.call(f1mPrefix + "_add", A, C, A_C), + cd.call(f1mPrefix + "_add", b, c, b_c), + cd.call(f1mPrefix + "_add", B, C, B_C), + + cd.call(f1mPrefix + "_add", aA, bB, aA_bB), + cd.call(f1mPrefix + "_add", aA, cC, aA_cC), + cd.call(f1mPrefix + "_add", bB, cC, bB_cC), + + cd.call(f1mPrefix + "_mul", b_c, B_C, r0), + cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), + cd.call(mulNonResidueFn, r0, r0), + cd.call(f1mPrefix + "_add", aA, r0, r0), + + cd.call(f1mPrefix + "_mul", a_b, A_B, r1), + cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), + cd.call(mulNonResidueFn, cC, AUX), + cd.call(f1mPrefix + "_add", r1, AUX, r1), + + cd.call(f1mPrefix + "_mul", a_c, A_C, r2), + cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), + cd.call(f1mPrefix + "_add", r2, bB, r2), + ); + + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const A = c.getLocal("x"); + const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const s0 = c.i32_const(module.alloc(f1n8)); + const ab = c.i32_const(module.alloc(f1n8)); + const s1 = c.i32_const(module.alloc(f1n8)); + const s2 = c.i32_const(module.alloc(f1n8)); + const bc = c.i32_const(module.alloc(f1n8)); + const s3 = c.i32_const(module.alloc(f1n8)); + const s4 = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + + c.call(f1mPrefix + "_square", A, s0), + c.call(f1mPrefix + "_mul", A, B, ab), + c.call(f1mPrefix + "_add", ab, ab, s1), + + c.call(f1mPrefix + "_sub", A, B, s2), + c.call(f1mPrefix + "_add", s2, C, s2), + c.call(f1mPrefix + "_square", s2, s2), + + c.call(f1mPrefix + "_mul", B, C, bc), + c.call(f1mPrefix + "_add", bc, bc, s3), + + c.call(f1mPrefix + "_square", C, s4), + + c.call(mulNonResidueFn, s3, r0), + c.call(f1mPrefix + "_add", s0, r0, r0), + + c.call(mulNonResidueFn, s4, r1), + c.call(f1mPrefix + "_add", s1, r1, r1), + + c.call(f1mPrefix + "_add", s0, s4, r2), + c.call(f1mPrefix + "_sub", s3, r2, r2), + c.call(f1mPrefix + "_add", s2, r2, r2), + c.call(f1mPrefix + "_add", s1, r2, r2), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1), + c.call(f1mPrefix+"_toMontgomery", x2, r2) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1), + c.call(f1mPrefix+"_fromMontgomery", x2, r2) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1), + c.call(f1mPrefix+"_copy", x2, r2), + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1), + ), + c.call(f1mPrefix+"_eq", x2, y2) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ), + c.call(f1mPrefix+"_isZero", x2) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + const t4 = c.i32_const(module.alloc(f1n8)); + const t5 = c.i32_const(module.alloc(f1n8)); + const c0 = c.i32_const(module.alloc(f1n8)); + const c1 = c.i32_const(module.alloc(f1n8)); + const c2 = c.i32_const(module.alloc(f1n8)); + const t6 = c.i32_const(module.alloc(f1n8)); + const AUX = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + c.call(f1mPrefix+"_square", x2, t2), + c.call(f1mPrefix+"_mul", x0, x1, t3), + c.call(f1mPrefix+"_mul", x0, x2, t4), + c.call(f1mPrefix+"_mul", x1, x2, t5), + + c.call(mulNonResidueFn, t5, c0), + c.call(f1mPrefix+"_sub", t0, c0, c0), + + c.call(mulNonResidueFn, t2, c1), + c.call(f1mPrefix+"_sub", c1, t3, c1), + + c.call(f1mPrefix+"_sub", t1, t4, c2), + + c.call(f1mPrefix+"_mul", x2, c1, t6), + c.call(f1mPrefix+"_mul", x1, c2, AUX), + c.call(f1mPrefix+"_add", t6, AUX, t6), + c.call(mulNonResidueFn, t6, t6), + c.call(f1mPrefix+"_mul", x0, c0, AUX), + c.call(f1mPrefix+"_add", AUX, t6, t6), + + c.call(f1mPrefix+"_inverse", t6, t6), + + c.call(f1mPrefix+"_mul", t6, c0, r0), + c.call(f1mPrefix+"_mul", t6, c1, r1), + c.call(f1mPrefix+"_mul", t6, c2, r2) + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); + + f.addCode( + c.ret( + c.i32_and( + c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1) + ), + c.call(f1mPrefix + "_isZero", x2) + ) + ) + ); + } + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildSign(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*3, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one" + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_isNegative"); + + return prefix; +}; + + +/***/ }), + +/***/ 93911: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(92096); +const utils = __webpack_require__(12333); + +module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { + + const n64f = module.modules[fPrefix].n64; + const n8f = n64f*8; + + const n64g = module.modules[gPrefix].n64; + const n8g = n64g*8; + + const q = module.modules[fPrefix].q; + + let rem = q.minus(bigInt(1)); + let maxBits = 0; + while (!rem.isOdd()) { + maxBits ++; + rem = rem.shiftRight(1); + } + + let nr = bigInt(2); + + while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); + + // console.log(nr); + + const w = new Array(maxBits+1); + w[maxBits] = nr.modPow(rem, q); + + let n=maxBits-1; + while (n>=0) { + w[n] = w[n+1].modPow(2, q); + n--; + } + + const bytes = []; + const R = bigInt(1).shiftLeft(n8f*8).mod(q); + + for (let i=0; i> i); + } + } + return r; + } + + const rtable = Array(256); + for (let i=0; i<256; i++) { + rtable[i] = rev(i); + } + + const REVTABLE = module.alloc(rtable); + + + function buildLog2() { + const f = module.addFunction(prefix+"__log2"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + f.addLocal("bits", "i32"); + f.addLocal("aux", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ) + ); + f.addCode(c.setLocal("bits", c.i32_const(0))); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_eqz(c.getLocal("aux")) + ), + + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("aux"), + c.i32_const(1) + ) + ), + + c.setLocal( + "bits", + c.i32_add( + c.getLocal("bits"), + c.i32_const(1) + ) + ), + + c.br(0) + ))); + + f.addCode(c.if( + c.i32_ne( + c.getLocal("n"), + c.i32_shl( + c.i32_const(1), + c.getLocal("bits") + ) + ), + c.unreachable() + )); + + f.addCode(c.if( + c.i32_gt_u( + c.getLocal("bits"), + c.i32_const(maxBits) + ), + c.unreachable() + )); + + f.addCode(c.getLocal("bits")); + } + + function buildFFT() { + const f = module.addFunction(prefix+"_fft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + + f.addLocal("bits", "i32"); + + const c = f.getCodeBuilder(); + + const One = c.i32_const(module.alloc(n8f)); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.call(fPrefix + "_one", One), + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(0), + One + ) + ); + + } + + function buildIFFT() { + const f = module.addFunction(prefix+"_ifft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("bits", "i32"); + f.addLocal("pInv2", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.setLocal( + "pInv2", + c.i32_add( + c.i32_const(INV2), + c.i32_mul( + c.getLocal("bits"), + c.i32_const(n8f) + ) + ) + ), + + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(1), + c.getLocal("pInv2") + ), + ); + } + + function buildRawFFT() { + const f = module.addFunction(prefix+"_rawfft"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); // 2 power + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + + f.addLocal("s", "i32"); + f.addLocal("k", "i32"); + f.addLocal("j", "i32"); + f.addLocal("m", "i32"); + f.addLocal("mdiv2", "i32"); + f.addLocal("n", "i32"); + f.addLocal("pwm", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call(prefix + "__reversePermutation", c.getLocal("px"), c.getLocal("bits")), + c.setLocal("n", c.i32_shl(c.i32_const(1), c.getLocal("bits"))), + c.setLocal("s", c.i32_const(1)), + c.block(c.loop( + c.br_if( + 1, + c.i32_gt_u( + c.getLocal("s"), + c.getLocal("bits") + ) + ), + c.setLocal("m", c.i32_shl(c.i32_const(1), c.getLocal("s"))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("s"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("k", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("k"), + c.getLocal("n") + ) + ), + + c.call(fPrefix + "_one", W), + + c.setLocal("mdiv2", c.i32_shr_u(c.getLocal("m"), c.i32_const(1)) ), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("j"), + c.getLocal("mdiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_add( + c.getLocal("k"), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.i32_mul( + c.getLocal("mdiv2"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("k", c.i32_add(c.getLocal("k"), c.getLocal("m"))), + c.br(0) + )), + + c.setLocal("s", c.i32_add(c.getLocal("s"), c.i32_const(1))), + c.br(0) + )), + c.call( + prefix + "__fftFinal", + c.getLocal("px"), + c.getLocal("bits"), + c.getLocal("reverse"), + c.getLocal("mulFactor") + ) + ); + } + + + function buildFinalInverse() { + const f = module.addFunction(prefix+"__fftFinal"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + f.addLocal("n", "i32"); + f.addLocal("ndiv2", "i32"); + f.addLocal("pInv2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("mask", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.if( + c.i32_and( + c.i32_eqz(c.getLocal("reverse")), + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")) + ), + c.ret([]) + ), + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + + c.setLocal("mask", c.i32_sub( c.getLocal("n") , c.i32_const(1))), + c.setLocal("i", c.i32_const(1)), + c.setLocal( + "ndiv2", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.getLocal("reverse"), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1") ), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")), + ], + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , T , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF , c.getLocal("idx1") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )), + + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF, c.getLocal("px") , c.getLocal("mulFactor"), c.getLocal("px")), + ...c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ) + ), + ...c.call(opGtimesF, c.getLocal("idx2"),c.getLocal("mulFactor"), c.getLocal("idx2")) + ] + ) + ); + } + + function buildReversePermutation() { + const f = module.addFunction(prefix+"__reversePermutation"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addLocal("n", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ri", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("ri", c.call(prefix + "__rev", c.getLocal("i"), c.getLocal("bits"))), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ri"), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.i32_lt_u( + c.getLocal("i"), + c.getLocal("ri") + ), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1")), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")) + ] + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )) + ); + } + + function buildRev() { + const f = module.addFunction(prefix+"__rev"); + f.addParam("x", "i32"); + f.addParam("bits", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_rotl( + c.i32_add( + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.getLocal("x"), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(24) + ), + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(8) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(16) + ), + ), + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(16) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(8) + ), + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(24) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + ) + ), + c.getLocal("bits") + ) + ); + } + + + function buildFFTJoin() { + const f = module.addFunction(prefix+"_fftJoin"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W, + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildFFTJoinExt() { + const f = module.addFunction(prefix+"_fftJoinExt"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + U + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pShiftToM"), + c.getLocal("idx2") + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + U, + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTJoinExtInv() { + const f = module.addFunction(prefix+"_fftJoinExtInv"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + U, + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pSConst"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + c.getLocal("idx1") + ), + + c.call( + gPrefix + "_sub", + U, + c.getLocal("idx1"), + c.getLocal("idx1") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pSConst"), + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildPrepareLagrangeEvaluation() { + const f = module.addFunction(prefix+"_prepareLagrangeEvaluation"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx2"), + U, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + U, + c.getLocal("pSConst"), + c.getLocal("idx1"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTMix() { + const f = module.addFunction(prefix+"_fftMix"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("exp", "i32"); + f.addLocal("nGroups", "i32"); + f.addLocal("nPerGroup", "i32"); + f.addLocal("nPerGroupDiv2", "i32"); + f.addLocal("pairOffset", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pwm", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("nPerGroup", c.i32_shl(c.i32_const(1), c.getLocal("exp"))), + c.setLocal("nPerGroupDiv2", c.i32_shr_u(c.getLocal("nPerGroup"), c.i32_const(1))), + c.setLocal("nGroups", c.i32_shr_u(c.getLocal("n"), c.getLocal("exp"))), + c.setLocal("pairOffset", c.i32_mul(c.getLocal("nPerGroupDiv2"), c.i32_const(n8g))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("exp"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nGroups") + ) + ), + c.call( fPrefix + "_one", W), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nPerGroupDiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_add( + c.i32_mul( + c.getLocal("i"), + c.getLocal("nPerGroup") + ), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.getLocal("pairOffset") + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + // Reverse all and multiply by factor + function buildFFTFinal() { + const f = module.addFunction(prefix+"_fftFinal"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("factor", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ndiv2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("ndiv2", c.i32_shr_u(c.getLocal("n"), c.i32_const(1))), + c.if( + c.i32_and( + c.getLocal("n"), + c.i32_const(1) + ), + c.call( + opGtimesF, + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + c.getLocal("factor"), + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + ), + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_sub( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("factor"), + T + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("factor"), + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + T, + c.getLocal("idx1"), + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + buildRev(); + buildReversePermutation(); + buildFinalInverse(); + buildRawFFT(); + buildLog2(); + buildFFT(); + buildIFFT(); + buildFFTJoin(); + buildFFTJoinExt(); + buildFFTJoinExtInv(); + buildFFTMix(); + buildFFTFinal(); + buildPrepareLagrangeEvaluation(); + + module.exportFunction(prefix+"_fft"); + module.exportFunction(prefix+"_ifft"); + module.exportFunction(prefix+"_rawfft"); + module.exportFunction(prefix+"_fftJoin"); + module.exportFunction(prefix+"_fftJoinExt"); + module.exportFunction(prefix+"_fftJoinExtInv"); + module.exportFunction(prefix+"_fftMix"); + module.exportFunction(prefix+"_fftFinal"); + module.exportFunction(prefix+"_prepareLagrangeEvaluation"); + +}; + + +/***/ }), + +/***/ 76754: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const utils = __webpack_require__(12333); + +module.exports = function buildInt(module, n64, _prefix) { + + const prefix = _prefix || "int"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = {}; + + const n32 = n64*2; + const n8 = n64*8; + + const one = module.alloc(n8, utils.bigInt2BytesLE(1, n8)); + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("px", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + f.addCode( + c.i64_store32( + c.getLocal("r"), + k*4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4*2-4, + c.getLocal(c0_old) + ) + ); + + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function _buildMul1() { + const f = module.addFunction(prefix+"__mul1"); + f.addParam("px", "i32"); + f.addParam("y", "i64"); + f.addParam("pr", "i32"); + f.addLocal("c", "i64"); + + const c = f.getCodeBuilder(); + + f.addCode(c.setLocal( + "c", + c.i64_mul( + c.i64_load32_u(c.getLocal("px"), 0, 0), + c.getLocal("y") + ) + )); + + f.addCode(c.i64_store32( + c.getLocal("pr"), + 0, + 0, + c.getLocal("c"), + )); + + for (let i=1; i3)&&(Y[eY]==0) ey--; + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(Y , c.getLocal("eY")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eY"), + c.i32_const(3) + ) + ) + ), + c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), + c.br(0) + ))); + + f.addCode( + c.setLocal( + "sy", + c.i64_add( + c.i64_load32_u( + c.i32_sub( + c.i32_add( Y, c.getLocal("eY")), + c.i32_const(3) + ), + 0, + 0 + ), + c.i64_const(1) + ) + ) + ); + + // Force a divide by 0 if quotien is 0 + f.addCode( + c.if( + c.i64_eq( + c.getLocal("sy"), + c.i64_const(1) + ), + c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) + ) + ); + + f.addCode(c.block(c.loop( + + // while (eX>7)&&(Y[eX]==0) ex--; + c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(R , c.getLocal("eX")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eX"), + c.i32_const(7) + ) + ) + ), + c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal( + "sx", + c.i64_load( + c.i32_sub( + c.i32_add( R, c.getLocal("eX")), + c.i32_const(7) + ), + 0, + 0 + ) + ), + + c.setLocal( + "sx", + c.i64_div_u( + c.getLocal("sx"), + c.getLocal("sy") + ) + ), + c.setLocal( + "ec", + c.i32_sub( + c.i32_sub( + c.getLocal("eX"), + c.getLocal("eY") + ), + c.i32_const(4) + ) + ), + + // While greater than 32 bits or ec is neg, shr and inc exp + c.block(c.loop( + c.br_if( + 1, + c.i32_and( + c.i64_eqz( + c.i64_and( + c.getLocal("sx"), + c.i64_const("0xFFFFFFFF00000000") + ) + ), + c.i32_ge_s( + c.getLocal("ec"), + c.i32_const(0) + ) + ) + ), + + c.setLocal( + "sx", + c.i64_shr_u( + c.getLocal("sx"), + c.i64_const(8) + ) + ), + + c.setLocal( + "ec", + c.i32_add( + c.getLocal("ec"), + c.i32_const(1) + ) + ), + c.br(0) + )), + + c.if( + c.i64_eqz(c.getLocal("sx")), + [ + ...c.br_if( + 2, + c.i32_eqz(c.call(prefix + "_gte", R, Y)) + ), + ...c.setLocal("sx", c.i64_const(1)), + ...c.setLocal("ec", c.i32_const(0)) + ] + ), + + c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), + c.drop(c.call( + prefix + "_sub", + R, + c.i32_sub(R2, c.getLocal("ec")), + R + )), + c.call( + prefix + "__add1", + c.i32_add(C, c.getLocal("ec")), + c.getLocal("sx") + ), + c.br(0) + ))); + } + + function buildInverseMod() { + + const f = module.addFunction(prefix+"_inverseMod"); + f.addParam("px", "i32"); + f.addParam("pm", "i32"); + f.addParam("pr", "i32"); + f.addLocal("t", "i32"); + f.addLocal("newt", "i32"); + f.addLocal("r", "i32"); + f.addLocal("qq", "i32"); + f.addLocal("qr", "i32"); + f.addLocal("newr", "i32"); + f.addLocal("swp", "i32"); + f.addLocal("x", "i32"); + f.addLocal("signt", "i32"); + f.addLocal("signnewt", "i32"); + f.addLocal("signx", "i32"); + + const c = f.getCodeBuilder(); + + const aux1 = c.i32_const(module.alloc(n8)); + const aux2 = c.i32_const(module.alloc(n8)); + const aux3 = c.i32_const(module.alloc(n8)); + const aux4 = c.i32_const(module.alloc(n8)); + const aux5 = c.i32_const(module.alloc(n8)); + const aux6 = c.i32_const(module.alloc(n8)); + const mulBuff = c.i32_const(module.alloc(n8*2)); + const aux7 = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("t", aux1), + c.call(prefix + "_zero", aux1), + c.setLocal("signt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("r", aux2), + c.call(prefix + "_copy", c.getLocal("pm"), aux2) + ); + + f.addCode( + c.setLocal("newt", aux3), + c.call(prefix + "_one", aux3), + c.setLocal("signnewt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("newr", aux4), + c.call(prefix + "_copy", c.getLocal("px"), aux4) + ); + + + + + f.addCode(c.setLocal("qq", aux5)); + f.addCode(c.setLocal("qr", aux6)); + f.addCode(c.setLocal("x", aux7)); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.call(prefix + "_isZero", c.getLocal("newr") ) + ), + c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), + + c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), + + c.if( + c.getLocal("signt"), + c.if( + c.getLocal("signnewt"), + c.if ( + c.call(prefix + "_gte", mulBuff, c.getLocal("t")), + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ], + ), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ), + c.if( + c.getLocal("signnewt"), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + c.if ( + c.call(prefix + "_gte", c.getLocal("t"), mulBuff), + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ) + ) + ), + + c.setLocal("swp", c.getLocal("t")), + c.setLocal("t", c.getLocal("newt")), + c.setLocal("newt", c.getLocal("x")), + c.setLocal("x", c.getLocal("swp")), + + c.setLocal("signt", c.getLocal("signnewt")), + c.setLocal("signnewt", c.getLocal("signx")), + + c.setLocal("swp", c.getLocal("r")), + c.setLocal("r", c.getLocal("newr")), + c.setLocal("newr", c.getLocal("qr")), + c.setLocal("qr", c.getLocal("swp")), + + c.br(0) + ))); + + f.addCode(c.if( + c.getLocal("signt"), + c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), + c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) + )); + } + + + buildCopy(); + buildZero(); + buildIsZero(); + buildOne(); + buildEq(); + buildGte(); + buildAdd(); + buildSub(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildDiv(); + buildInverseMod(); + module.exportFunction(prefix+"_copy"); + module.exportFunction(prefix+"_zero"); + module.exportFunction(prefix+"_one"); + module.exportFunction(prefix+"_isZero"); + module.exportFunction(prefix+"_eq"); + module.exportFunction(prefix+"_gte"); + module.exportFunction(prefix+"_add"); + module.exportFunction(prefix+"_sub"); + module.exportFunction(prefix+"_mul"); + module.exportFunction(prefix+"_square"); + module.exportFunction(prefix+"_squareOld"); + module.exportFunction(prefix+"_div"); + module.exportFunction(prefix+"_inverseMod"); + + return prefix; +}; + + +/***/ }), + +/***/ 74911: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { + + const n64g = module.modules[prefix].n64; + const n8g = n64g*8; + + function buildGetChunk() { + const f = module.addFunction(fnName + "_getChunk"); + f.addParam("pScalar", "i32"); + f.addParam("scalarSize", "i32"); // Number of bytes of the scalar + f.addParam("startBit", "i32"); // Bit to start extract + f.addParam("chunkSize", "i32"); // Chunk size in bits + f.addLocal("bitsToEnd", "i32"); + f.addLocal("mask", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("bitsToEnd", + c.i32_sub( + c.i32_mul( + c.getLocal("scalarSize"), + c.i32_const(8) + ), + c.getLocal("startBit") + ) + ), + c.if( + c.i32_gt_s( + c.getLocal("chunkSize"), + c.getLocal("bitsToEnd") + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("bitsToEnd") + ), + c.i32_const(1) + ) + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ) + ), + c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("pScalar"), + c.i32_shr_u( + c.getLocal("startBit"), + c.i32_const(3) + ) + ), + 0, // offset + 0 // align to byte. + ), + c.i32_and( + c.getLocal("startBit"), + c.i32_const(0x7) + ) + ), + c.getLocal("mask") + ) + ); + } + + function buildMutiexpChunk() { + const f = module.addFunction(fnName + "_chunk"); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("startBit", "i32"); // bit where it starts the chunk + f.addParam("chunkSize", "i32"); // bit where it starts the chunk + f.addParam("pr", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("n")), + [ + ...c.call(prefix + "_zero", c.getLocal("pr")), + ...c.ret([]) + ] + ), + + // Allocate memory + + c.setLocal( + "nTable", + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ) + ), + c.setLocal("pTable", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("nTable"), + c.i32_const(n8g) + ) + ) + ), + + // Reset Table + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nTable") + ) + ), + + c.call( + prefix + "_zero", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("j"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + // Distribute elements + c.setLocal("itBase", c.getLocal("pBases")), + c.setLocal("itScalar", c.getLocal("pScalars")), + c.setLocal("endScalar", + c.i32_add( + c.getLocal("pScalars"), + c.i32_mul( + c.getLocal("n"), + c.getLocal("scalarSize") + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("itScalar"), + c.getLocal("endScalar") + ) + ), + + c.setLocal( + "idx", + c.call(fnName + "_getChunk", + c.getLocal("itScalar"), + c.getLocal("scalarSize"), + c.getLocal("startBit"), + c.getLocal("chunkSize") + ) + ), + + c.if( + c.getLocal("idx"), + [ + ...c.setLocal( + "pIdxTable", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.i32_sub( + c.getLocal("idx"), + c.i32_const(1) + ), + c.i32_const(n8g) + ) + ) + ), + ...c.call( + opAdd, + c.getLocal("pIdxTable"), + c.getLocal("itBase"), + c.getLocal("pIdxTable"), + ) + ] + ), + + c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), + c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), + c.br(0) + )), + + c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), + c.call( + prefix + "_copy", + c.getLocal("pTable"), + c.getLocal("pr") + ), + + + c.i32_store( + c.i32_const(0), + c.getLocal("pTable") + ) + + ); + } + + function buildMultiexp() { + const f = module.addFunction(fnName); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("pr", "i32"); + f.addLocal("chunkSize", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("itBit", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8g)); + + const pTSizes = module.alloc([ + 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 16, 16, 15, 14, 13, 13, + 12, 11, 10, 9, 8, 7, 7, 6, + 5 , 4, 3, 2, 1, 1, 1, 1 + ]); + + f.addCode( + c.call(prefix + "_zero", c.getLocal("pr")), + c.if( + c.i32_eqz(c.getLocal("n")), + c.ret([]) + ), + c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), + c.setLocal( + "nChunks", + c.i32_add( + c.i32_div_u( + c.i32_sub( + c.i32_shl( + c.getLocal("scalarSize"), + c.i32_const(3) + ), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ), + + + // Allocate memory + + c.setLocal( + "itBit", + c.i32_mul( + c.i32_sub( + c.getLocal("nChunks"), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_lt_s( + c.getLocal("itBit"), + c.i32_const(0) + ) + ), + + // Double nChunk times + c.if( + c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), + [ + ...c.setLocal("j", c.i32_const(0)), + ...c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("chunkSize") + ) + ), + + c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )) + ] + ), + + c.call( + fnName + "_chunk", + c.getLocal("pBases"), + c.getLocal("pScalars"), + c.getLocal("scalarSize"), + c.getLocal("n"), + c.getLocal("itBit"), + c.getLocal("chunkSize"), + aux + ), + + c.call( + prefix + "_add", + c.getLocal("pr"), + aux, + c.getLocal("pr") + ), + c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), + c.br(0) + )) + ); + } + + function buildReduceTable() { + const f = module.addFunction(fnName + "_reduceTable"); + f.addParam("pTable", "i32"); + f.addParam("p", "i32"); // Number of bits of the table + f.addLocal("half", "i32"); + f.addLocal("it1", "i32"); + f.addLocal("it2", "i32"); + f.addLocal("pAcc", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eq(c.getLocal("p"), c.i32_const(1)), + c.ret([]) + ), + c.setLocal( + "half", + c.i32_shl( + c.i32_const(1), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ), + + c.setLocal("it1", c.getLocal("pTable")), + c.setLocal( + "it2", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("half"), + c.i32_const(n8g) + ) + ) + ), + c.setLocal("pAcc", + c.i32_sub( + c.getLocal("it2"), + c.i32_const(n8g) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it1"), + c.getLocal("pAcc") + ) + ), + c.call( + prefix + "_add", + c.getLocal("it1"), + c.getLocal("it2"), + c.getLocal("it1") + ), + c.call( + prefix + "_add", + c.getLocal("pAcc"), + c.getLocal("it2"), + c.getLocal("pAcc") + ), + c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), + c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), + c.br(0) + )), + + c.call( + fnName + "_reduceTable", + c.getLocal("pTable"), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("p"))), + c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) + ); + } + + buildGetChunk(); + buildReduceTable(); + buildMutiexpChunk(); + buildMultiexp(); + + module.exportFunction(fnName); + module.exportFunction(fnName +"_chunk"); + + +}; + + + + + +/***/ }), + +/***/ 2896: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildPol(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("lastp", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("p", c.getLocal("px")), + c.setLocal( + "lastp", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("p"), + c.getLocal("lastp") + ) + ), + c.call(prefixField + "_zero", c.getLocal("p")), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildConstructLC() { + const f = module.addFunction(prefix+"_constructLC"); + f.addParam("ppolynomials", "i32"); + f.addParam("psignals", "i32"); + f.addParam("nSignals", "i32"); + f.addParam("pres", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pp", "i32"); + f.addLocal("ps", "i32"); + f.addLocal("pd", "i32"); + f.addLocal("ncoefs", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.setLocal("pp", c.getLocal("ppolynomials")), + c.setLocal("ps", c.getLocal("psignals")), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nSignals") + ) + ), + + c.setLocal("ncoefs", c.i32_load(c.getLocal("pp"))), + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("ncoefs") + ) + ), + + c.setLocal( + "pd", + c.i32_add( + c.getLocal("pres"), + c.i32_mul( + c.i32_load(c.getLocal("pp")), + c.i32_const(n8) + ) + ) + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + + c.call( + prefixField + "_mul", + c.getLocal("ps"), + c.getLocal("pp"), + aux + ), + + c.call( + prefixField + "_add", + aux, + c.getLocal("pd"), + c.getLocal("pd") + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(n8))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + } + + buildZero(); + buildConstructLC(); + + + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_constructLC"); + + return prefix; + + + + +}; + + +/***/ }), + +/***/ 10637: +/***/ ((module) => { + + +module.exports = function buildQAP(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildBuildABC() { + const f = module.addFunction(prefix+"_buildABC"); + f.addParam("pCoefs", "i32"); + f.addParam("nCoefs", "i32"); + f.addParam("pWitness", "i32"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("offsetOut", "i32"); + f.addParam("nOut", "i32"); + f.addParam("offsetWitness", "i32"); + f.addParam("nWitness", "i32"); + f.addLocal("it", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("last", "i32"); + f.addLocal("m", "i32"); + f.addLocal("c", "i32"); + f.addLocal("s", "i32"); + f.addLocal("pOut", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + + // Set output a and b to 0 + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call(prefixField + "_zero", c.getLocal("ita")), + c.call(prefixField + "_zero", c.getLocal("itb")), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.br(0) + )), + + + c.setLocal("it", c.getLocal("pCoefs")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pCoefs"), + c.i32_mul( + c.getLocal("nCoefs"), + c.i32_const(n8+12) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it"), + c.getLocal("last") + ) + ), + c.setLocal( + "s", + c.i32_load(c.getLocal("it"), 8) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("s"), + c.getLocal("offsetWitness"), + ), + c.i32_ge_u( + c.getLocal("s"), + c.i32_add( + c.getLocal("offsetWitness"), + c.getLocal("nWitness"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + + c.setLocal( + "m", + c.i32_load(c.getLocal("it")) + ), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(0)), + c.setLocal("pOut", c.getLocal("pA")), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(1)), + c.setLocal("pOut", c.getLocal("pB")), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ) + ), + c.setLocal( + "c", + c.i32_load(c.getLocal("it"), 4) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("c"), + c.getLocal("offsetOut"), + ), + c.i32_ge_u( + c.getLocal("c"), + c.i32_add( + c.getLocal("offsetOut"), + c.getLocal("nOut"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + c.setLocal( + "pOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("c"), + c.getLocal("offsetOut") + ), + c.i32_const(n8) + ) + ) + ), + c.call( + prefixField + "_mul", + c.i32_add( + c.getLocal("pWitness"), + c.i32_mul( + c.i32_sub(c.getLocal("s"), c.getLocal("offsetWitness")), + c.i32_const(n8) + ) + ), + c.i32_add( c.getLocal("it"), c.i32_const(12)), + aux + ), + c.call( + prefixField + "_add", + c.getLocal("pOut"), + aux, + c.getLocal("pOut"), + ), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + c.br(0) + )), + + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("it", c.getLocal("pC")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("it") + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8))), + c.br(0) + )), + + ); + } + + function buildJoinABC() { + const f = module.addFunction(prefix+"_joinABC"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("n", "i32"); + f.addParam("pP", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itc", "i32"); + f.addLocal("itp", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("itc", c.getLocal("pC")), + c.setLocal("itp", c.getLocal("pP")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + aux + ), + c.call( + prefixField + "_sub", + aux, + c.getLocal("itc"), + c.getLocal("itp"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itc", c.i32_add(c.getLocal("itc"), c.i32_const(n8))), + c.setLocal("itp", c.i32_add(c.getLocal("itp"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildBatchAdd() { + const f = module.addFunction(prefix+"_batchAdd"); + f.addParam("pa", "i32"); + f.addParam("pb", "i32"); + f.addParam("n", "i32"); + f.addParam("pr", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itr", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("ita", c.getLocal("pa")), + c.setLocal("itb", c.getLocal("pb")), + c.setLocal("itr", c.getLocal("pr")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pa"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_add", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("itr"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itr", c.i32_add(c.getLocal("itr"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + buildBuildABC(); + buildJoinABC(); + buildBatchAdd(); + + module.exportFunction(prefix + "_buildABC"); + module.exportFunction(prefix + "_joinABC"); + module.exportFunction(prefix + "_batchAdd"); + + return prefix; + +}; + + + +/***/ }), + +/***/ 50345: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("i", "i32"); + f.addLocal("b", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ) + ); + f.addCode(c.call(opCopy, c.getLocal("base"), aux)); + f.addCode(c.call(opInit, c.getLocal("r"))); + f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); + f.addCode(c.block(c.loop( + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + + c.setLocal( + "b", + c.i32_load8_u( + c.i32_add( + c.getLocal("scalar"), + c.getLocal("i") + ) + ) + ), + ...innerLoop(), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.br(0) + ))); + + + function innerLoop() { + const code = []; + for (let i=0; i<8; i++) { + code.push( + ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), + ...c.if( + c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), + [ + ...c.setLocal( + "b", + c.i32_sub( + c.getLocal("b"), + c.i32_const(0x80 >> i) + ) + ), + ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) + ] + ) + ); + } + return code; + } + +}; + + +/***/ }), + +/***/ 33972: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("old0", "i32"); + f.addLocal("nbits", "i32"); + f.addLocal("i", "i32"); + f.addLocal("last", "i32"); + f.addLocal("cur", "i32"); + f.addLocal("carry", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + function getBit(IDX) { + return c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("scalar"), + c.i32_and( + c.i32_shr_u( + IDX, + c.i32_const(3) + ), + c.i32_const(0xFFFFFFFC) + ) + ) + ), + c.i32_and( + IDX, + c.i32_const(0x1F) + ) + ), + c.i32_const(1) + ); + } + + function pushBit(b) { + return [ + ...c.i32_store8( + c.getLocal("p"), + c.i32_const(b) + ), + ...c.setLocal( + "p", + c.i32_add( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ]; + } + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ), + c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), + c.setLocal("old0", c.i32_load(c.i32_const(0))), + c.setLocal("p", c.getLocal("old0")), + c.i32_store( + c.i32_const(0), + c.i32_and( + c.i32_add( + c.i32_add( + c.getLocal("old0"), + c.i32_const(32) + ), + c.getLocal("nbits") + ), + c.i32_const(0xFFFFFFF8) + ) + ), + c.setLocal("i", c.i32_const(1)), + + c.setLocal("last",getBit(c.i32_const(0))), + c.setLocal("carry",c.i32_const(0)), + + c.block(c.loop( + c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + + c.setLocal("cur", getBit(c.getLocal("i"))), + c.if( c.getLocal("last"), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(1) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(1) + ], + ), + ), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.if( c.getLocal("last"), + c.if(c.getLocal("carry"), + [ + ...pushBit(255), + ...pushBit(0), + ...pushBit(1) + ] + , + [ + ...pushBit(1) + ], + ), + c.if(c.getLocal("carry"), + [ + ...pushBit(0), + ...pushBit(1) + ] + ), + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + + // p already points to the last bit + + c.call(opCopy, c.getLocal("base"), aux), + + c.call(opInit, c.getLocal("r")), + + c.block(c.loop( + + + c.call(opAA, c.getLocal("r"), c.getLocal("r")), + + + c.setLocal("cur", + c.i32_load8_u( + c.getLocal("p") + ) + ), + + c.if( + c.getLocal("cur"), + c.if( + c.i32_eq(c.getLocal("cur"), c.i32_const(1)), + c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), + c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), + ) + ), + + c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + + )), + + c.i32_store( c.i32_const(0), c.getLocal("old0")) + + ); + +}; + + +/***/ }), + +/***/ 12333: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(92096); + +exports.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = bigInt(_a); + for (let i=0; i { + +"use strict"; + + +var forEach = __webpack_require__(82682); +var availableTypedArrays = __webpack_require__(39209); +var callBind = __webpack_require__(10487); +var callBound = __webpack_require__(38075); +var gOPD = __webpack_require__(75795); + +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(49092)(); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; + +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); +} + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; + + +/***/ }), + +/***/ 57510: +/***/ ((module) => { + +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + + +/***/ }), + +/***/ 40259: +/***/ ((module) => { + +"use strict"; + +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} + + +/***/ }), + +/***/ 28799: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + __webpack_require__(40259)(Yallist) +} catch (er) {} + + +/***/ }), + +/***/ 5183: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 78982: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 47790: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 73776: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 21638: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 92668: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 77965: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 66089: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 79368: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 23276: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 59676: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 64688: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 51069: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 15340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 79838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 59817: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 71281: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 29530: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 60684: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 26840: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 60513: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2378: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 21628: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 60290: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 47882: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 39209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(76578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }), + +/***/ 89082: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + HI: () => (/* reexport */ mimcsponge_buildMimcSponge), + vu: () => (/* reexport */ pedersen_hash_buildPedersenHash) +}); + +// UNUSED EXPORTS: SMT, SMTMemDb, buildBabyjub, buildEddsa, buildMimc7, buildPoseidon, buildPoseidonOpt, buildPoseidonReference, buildPoseidonWasm, buildSMT, evmasm, mimc7Contract, mimcSpongecontract, newMemEmptyTrie, poseidonContract + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_native.js +var scalar_native_namespaceObject = {}; +__webpack_require__.r(scalar_native_namespaceObject); +__webpack_require__.d(scalar_native_namespaceObject, { + abs: () => (abs), + add: () => (add), + band: () => (band), + bitLength: () => (bitLength), + bits: () => (bits), + bor: () => (bor), + bxor: () => (bxor), + div: () => (div), + e: () => (e), + eq: () => (eq), + exp: () => (exp), + fromArray: () => (fromArray), + fromString: () => (fromString), + geq: () => (geq), + gt: () => (gt), + isNegative: () => (isNegative), + isOdd: () => (isOdd), + isZero: () => (isZero), + land: () => (land), + leq: () => (leq), + lnot: () => (lnot), + lor: () => (lor), + lt: () => (lt), + mod: () => (mod), + mul: () => (mul), + naf: () => (naf), + neg: () => (neg), + neq: () => (neq), + pow: () => (pow), + shiftLeft: () => (shiftLeft), + shiftRight: () => (shiftRight), + shl: () => (shl), + shr: () => (shr), + square: () => (square), + sub: () => (sub), + toArray: () => (toArray), + toNumber: () => (toNumber) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_bigint.js +var scalar_bigint_namespaceObject = {}; +__webpack_require__.r(scalar_bigint_namespaceObject); +__webpack_require__.d(scalar_bigint_namespaceObject, { + abs: () => (scalar_bigint_abs), + add: () => (scalar_bigint_add), + band: () => (scalar_bigint_band), + bitLength: () => (scalar_bigint_bitLength), + bits: () => (scalar_bigint_bits), + bor: () => (scalar_bigint_bor), + bxor: () => (scalar_bigint_bxor), + div: () => (scalar_bigint_div), + e: () => (scalar_bigint_e), + eq: () => (scalar_bigint_eq), + exp: () => (scalar_bigint_exp), + fromArray: () => (scalar_bigint_fromArray), + fromString: () => (scalar_bigint_fromString), + geq: () => (scalar_bigint_geq), + gt: () => (scalar_bigint_gt), + isNegative: () => (scalar_bigint_isNegative), + isOdd: () => (scalar_bigint_isOdd), + isZero: () => (scalar_bigint_isZero), + land: () => (scalar_bigint_land), + leq: () => (scalar_bigint_leq), + lnot: () => (scalar_bigint_lnot), + lor: () => (scalar_bigint_lor), + lt: () => (scalar_bigint_lt), + mod: () => (scalar_bigint_mod), + mul: () => (scalar_bigint_mul), + naf: () => (scalar_bigint_naf), + neg: () => (scalar_bigint_neg), + neq: () => (scalar_bigint_neq), + pow: () => (scalar_bigint_pow), + shiftLeft: () => (scalar_bigint_shiftLeft), + shiftRight: () => (scalar_bigint_shiftRight), + shl: () => (scalar_bigint_shl), + shr: () => (scalar_bigint_shr), + square: () => (scalar_bigint_square), + sub: () => (scalar_bigint_sub), + toArray: () => (scalar_bigint_toArray), + toNumber: () => (scalar_bigint_toNumber) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar.js +var scalar_namespaceObject = {}; +__webpack_require__.r(scalar_namespaceObject); +__webpack_require__.d(scalar_namespaceObject, { + abs: () => (scalar_abs), + add: () => (scalar_add), + band: () => (scalar_band), + bitLength: () => (scalar_bitLength), + bits: () => (scalar_bits), + bor: () => (scalar_bor), + bxor: () => (scalar_bxor), + div: () => (scalar_div), + e: () => (scalar_e), + eq: () => (scalar_eq), + exp: () => (scalar_exp), + fromArray: () => (scalar_fromArray), + fromRprBE: () => (fromRprBE), + fromRprLE: () => (fromRprLE), + fromString: () => (scalar_fromString), + geq: () => (scalar_geq), + gt: () => (scalar_gt), + isNegative: () => (scalar_isNegative), + isOdd: () => (scalar_isOdd), + isZero: () => (scalar_isZero), + land: () => (scalar_land), + leq: () => (scalar_leq), + lnot: () => (scalar_lnot), + lor: () => (scalar_lor), + lt: () => (scalar_lt), + mod: () => (scalar_mod), + mul: () => (scalar_mul), + naf: () => (scalar_naf), + neg: () => (scalar_neg), + neq: () => (scalar_neq), + one: () => (one), + pow: () => (scalar_pow), + shiftLeft: () => (scalar_shiftLeft), + shiftRight: () => (scalar_shiftRight), + shl: () => (scalar_shl), + shr: () => (scalar_shr), + square: () => (scalar_square), + sub: () => (scalar_sub), + toArray: () => (scalar_toArray), + toLEBuff: () => (toLEBuff), + toNumber: () => (scalar_toNumber), + toRprBE: () => (toRprBE), + toRprLE: () => (toRprLE), + toString: () => (scalar_toString), + zero: () => (zero) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_native.js +var utils_native_namespaceObject = {}; +__webpack_require__.r(utils_native_namespaceObject); +__webpack_require__.d(utils_native_namespaceObject, { + beBuff2int: () => (beBuff2int), + beInt2Buff: () => (beInt2Buff), + leBuff2int: () => (leBuff2int), + leInt2Buff: () => (leInt2Buff), + stringifyBigInts: () => (stringifyBigInts), + stringifyFElements: () => (stringifyFElements), + unstringifyBigInts: () => (unstringifyBigInts), + unstringifyFElements: () => (unstringifyFElements) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_bigint.js +var utils_bigint_namespaceObject = {}; +__webpack_require__.r(utils_bigint_namespaceObject); +__webpack_require__.d(utils_bigint_namespaceObject, { + beBuff2int: () => (utils_bigint_beBuff2int), + beInt2Buff: () => (utils_bigint_beInt2Buff), + leBuff2int: () => (utils_bigint_leBuff2int), + leInt2Buff: () => (utils_bigint_leInt2Buff), + stringifyBigInts: () => (utils_bigint_stringifyBigInts), + unstringifyBigInts: () => (utils_bigint_unstringifyBigInts) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils.js +var utils_namespaceObject = {}; +__webpack_require__.r(utils_namespaceObject); +__webpack_require__.d(utils_namespaceObject, { + array2buffer: () => (array2buffer), + beBuff2int: () => (utils_beBuff2int), + beInt2Buff: () => (utils_beInt2Buff), + bitReverse: () => (bitReverse), + buffReverseBits: () => (buffReverseBits), + buffer2array: () => (buffer2array), + leBuff2int: () => (utils_leBuff2int), + leInt2Buff: () => (utils_leInt2Buff), + log2: () => (utils_log2), + stringifyBigInts: () => (utils_stringifyBigInts), + stringifyFElements: () => (utils_stringifyFElements), + unstringifyBigInts: () => (utils_unstringifyBigInts), + unstringifyFElements: () => (utils_unstringifyFElements) +}); + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_native.js +/* global BigInt */ +const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; + +function fromString(s, radix) { + if ((!radix)||(radix==10)) { + return BigInt(s); + } else if (radix==16) { + if (s.slice(0,2) == "0x") { + return BigInt(s); + } else { + return BigInt("0x"+s); + } + } +} + +const e = fromString; + +function fromArray(a, radix) { + let acc =BigInt(0); + radix = BigInt(radix); + for (let i=0; i> BigInt(n); +} + +const shl = shiftLeft; +const shr = shiftRight; + +function isOdd(a) { + return (BigInt(a) & BigInt(1)) == BigInt(1); +} + + +function naf(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + const z = 2 - Number(E % BigInt(4)); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + + +function bits(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + res.push(1); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + +function toNumber(s) { + if (s>BigInt(Number.MAX_SAFE_INTEGER )) { + throw new Error("Number too big"); + } + return Number(s); +} + +function toArray(s, radix) { + const res = []; + let rem = BigInt(s); + radix = BigInt(radix); + while (rem) { + res.unshift( Number(rem % radix)); + rem = rem / radix; + } + return res; +} + + +function add(a, b) { + return BigInt(a) + BigInt(b); +} + +function sub(a, b) { + return BigInt(a) - BigInt(b); +} + +function neg(a) { + return -BigInt(a); +} + +function mul(a, b) { + return BigInt(a) * BigInt(b); +} + +function square(a) { + return BigInt(a) * BigInt(a); +} + +function pow(a, b) { + return BigInt(a) ** BigInt(b); +} + +function exp(a, b) { + return BigInt(a) ** BigInt(b); +} + +function abs(a) { + return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); +} + +function div(a, b) { + return BigInt(a) / BigInt(b); +} + +function mod(a, b) { + return BigInt(a) % BigInt(b); +} + +function eq(a, b) { + return BigInt(a) == BigInt(b); +} + +function neq(a, b) { + return BigInt(a) != BigInt(b); +} + +function lt(a, b) { + return BigInt(a) < BigInt(b); +} + +function gt(a, b) { + return BigInt(a) > BigInt(b); +} + +function leq(a, b) { + return BigInt(a) <= BigInt(b); +} + +function geq(a, b) { + return BigInt(a) >= BigInt(b); +} + +function band(a, b) { + return BigInt(a) & BigInt(b); +} + +function bor(a, b) { + return BigInt(a) | BigInt(b); +} + +function bxor(a, b) { + return BigInt(a) ^ BigInt(b); +} + +function land(a, b) { + return BigInt(a) && BigInt(b); +} + +function lor(a, b) { + return BigInt(a) || BigInt(b); +} + +function lnot(a) { + return !BigInt(a); +} + + +// EXTERNAL MODULE: ./node_modules/big-integer/BigInteger.js +var BigInteger = __webpack_require__(92096); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_bigint.js + + +function scalar_bigint_fromString(s, radix) { + if (typeof s == "string") { + if (s.slice(0,2) == "0x") { + return BigInteger(s.slice(2), 16); + } else { + return BigInteger(s,radix); + } + } else { + return BigInteger(s, radix); + } +} + +const scalar_bigint_e = scalar_bigint_fromString; + +function scalar_bigint_fromArray(a, radix) { + return BigInteger.fromArray(a, radix); +} + +function scalar_bigint_bitLength(a) { + return BigInteger(a).bitLength(); +} + +function scalar_bigint_isNegative(a) { + return BigInteger(a).isNegative(); +} + +function scalar_bigint_isZero(a) { + return BigInteger(a).isZero(); +} + +function scalar_bigint_shiftLeft(a, n) { + return BigInteger(a).shiftLeft(n); +} + +function scalar_bigint_shiftRight(a, n) { + return BigInteger(a).shiftRight(n); +} + +const scalar_bigint_shl = scalar_bigint_shiftLeft; +const scalar_bigint_shr = scalar_bigint_shiftRight; + +function scalar_bigint_isOdd(a) { + return BigInteger(a).isOdd(); +} + + +function scalar_bigint_naf(n) { + let E = BigInteger(n); + const res = []; + while (E.gt(BigInteger.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function scalar_bigint_bits(n) { + let E = BigInteger(n); + const res = []; + while (E.gt(BigInteger.zero)) { + if (E.isOdd()) { + res.push(1); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function scalar_bigint_toNumber(s) { + if (!s.lt(BigInteger("9007199254740992", 10))) { + throw new Error("Number too big"); + } + return s.toJSNumber(); +} + +function scalar_bigint_toArray(s, radix) { + return BigInteger(s).toArray(radix); +} + +function scalar_bigint_add(a, b) { + return BigInteger(a).add(BigInteger(b)); +} + +function scalar_bigint_sub(a, b) { + return BigInteger(a).minus(BigInteger(b)); +} + +function scalar_bigint_neg(a) { + return BigInteger.zero.minus(BigInteger(a)); +} + +function scalar_bigint_mul(a, b) { + return BigInteger(a).times(BigInteger(b)); +} + +function scalar_bigint_square(a) { + return BigInteger(a).square(); +} + +function scalar_bigint_pow(a, b) { + return BigInteger(a).pow(BigInteger(b)); +} + +function scalar_bigint_exp(a, b) { + return BigInteger(a).pow(BigInteger(b)); +} + +function scalar_bigint_abs(a) { + return BigInteger(a).abs(); +} + +function scalar_bigint_div(a, b) { + return BigInteger(a).divide(BigInteger(b)); +} + +function scalar_bigint_mod(a, b) { + return BigInteger(a).mod(BigInteger(b)); +} + +function scalar_bigint_eq(a, b) { + return BigInteger(a).eq(BigInteger(b)); +} + +function scalar_bigint_neq(a, b) { + return BigInteger(a).neq(BigInteger(b)); +} + +function scalar_bigint_lt(a, b) { + return BigInteger(a).lt(BigInteger(b)); +} + +function scalar_bigint_gt(a, b) { + return BigInteger(a).gt(BigInteger(b)); +} + +function scalar_bigint_leq(a, b) { + return BigInteger(a).leq(BigInteger(b)); +} + +function scalar_bigint_geq(a, b) { + return BigInteger(a).geq(BigInteger(b)); +} + +function scalar_bigint_band(a, b) { + return BigInteger(a).and(BigInteger(b)); +} + +function scalar_bigint_bor(a, b) { + return BigInteger(a).or(BigInteger(b)); +} + +function scalar_bigint_bxor(a, b) { + return BigInteger(a).xor(BigInteger(b)); +} + +function scalar_bigint_land(a, b) { + return (!BigInteger(a).isZero()) && (!BigInteger(b).isZero()); +} + +function scalar_bigint_lor(a, b) { + return (!BigInteger(a).isZero()) || (!BigInteger(b).isZero()); +} + +function scalar_bigint_lnot(a) { + return BigInteger(a).isZero(); +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar.js + + + + +const supportsNativeBigInt = typeof BigInt === "function"; + +let scalar_Scalar = {}; +if (supportsNativeBigInt) { + Object.assign(scalar_Scalar, scalar_native_namespaceObject); +} else { + Object.assign(scalar_Scalar, scalar_bigint_namespaceObject); +} + + +// Returns a buffer with Little Endian Representation +scalar_Scalar.toRprLE = function rprBE(buff, o, e, n8) { + const s = "0000000" + e.toString(16); + const v = new Uint32Array(buff.buffer, o, n8/4); + const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; + for (let i=0; i> 5)+1; // Number of 32bit words; + for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); + return scalar_Scalar.fromString(a.join(""), 16); +}; + +// Pases a buffer with Big Endian Representation +scalar_Scalar.fromRprBE = function rprLEM(buff, o, n8) { + n8 = n8 || buff.byteLength; + o = o || 0; + const v = new DataView(buff.buffer, buff.byteOffset + o, n8); + const a = new Array(n8/4); + for (let i=0; i. +*/ + +/* + This library does operations on polynomials with coefficients in a field F. + + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ + +class PolField { + constructor (F) { + this.F = F; + + let rem = F.sqrt_t; + let s = F.sqrt_s; + + const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(five, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; + } + + + this.roots = []; +/* for (let i=0; i<16; i++) { + let r = this.F.one; + n = 1 << i; + const rootsi = new Array(n); + for (let j=0; j this.F.sqrt_s) n = this.s; + for (let i=n; (i>=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j a.length) { + [b, a] = [a, b]; + } + + if ((b.length <= 2) || (b.length < log2(a.length))) { + return this.mulNormal(a,b); + } else { + return this.mulFFT(a,b); + } + } + + mulNormal(a, b) { + let res = []; + for (let i=0; i0) { + const z = new Array(n).fill(this.F.zero); + return z.concat(p); + } else { + if (-n >= p.length) return []; + return p.slice(-n); + } + } + + eval2(p, x) { + let v = this.F.zero; + let ix = this.F.one; + for (let i=0; i> 1), + F.mul( + x, + _eval(p, newX, offset+step , step << 1, n >> 1))); + return res; + } + } + + lagrange(points) { + let roots = [this.F.one]; + for (let i=0; i> 1; + const p1 = this._fft(pall, bits-1, offset, step*2); + const p2 = this._fft(pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + let m= this.F.one; + for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; + return p.slice(0, i+1); + } + + eq(a, b) { + const pa = this.reduce(a); + const pb = this.reduce(b); + + if (pa.length != pb.length) return false; + for (let i=0; i=0; i--) { + res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); + } + return res; + } + + _next2Power(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + toString(p) { + const ap = this.normalize(p); + let S = ""; + for (let i=ap.length-1; i>=0; i--) { + if (!this.F.eq(p[i], this.F.zero)) { + if (S!="") S += " + "; + S = S + p[i].toString(10); + if (i>0) { + S = S + "x"; + if (i>1) { + S = S + "^" +i; + } + } + } + } + return S; + } + + normalize(p) { + const res = new Array(p.length); + for (let i=0; i + // rec = x^(k-2-scaleV)/ v + // + // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => + // res = rec * x^(m - (2*k-2 - scaleV)) => + // res = rec * x^(m - 2*k + 2 + scaleV) + + const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); + const res = this.scaleX(rec, m - 2*k + 2 + scaleV); + + return res; + } + + div(_u, _v) { + if (_u.length < _v.length) return []; + const kbits = log2(_v.length-1)+1; + const k = 1 << kbits; + + const u = this.scaleX(_u, k-_v.length); + const v = this.scaleX(_v, k-_v.length); + + const n = v.length-1; + let m = u.length-1; + + const s = this._reciprocal(v, kbits); + let t; + if (m>2*n) { + t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); + } + + let q = []; + let rem = u; + let us, ut; + let finish = false; + + while (!finish) { + us = this.mul(rem, s); + q = this.add(q, this.scaleX(us, -2*n)); + + if ( m > 2*n ) { + ut = this.mul(rem, t); + rem = this.scaleX(ut, -2*n); + m = rem.length-1; + } else { + finish = true; + } + } + + return q; + } + + + // returns the ith nth-root of one + oneRoot(n, i) { + let nbits = log2(n-1)+1; + let res = this.F.one; + let r = i; + + if(i>=n) { + throw new Error("Given 'i' should be lower than 'n'"); + } + else if (1<0) { + if (r & 1 == 1) { + res = this.F.mul(res, this.w[nbits]); + } + r = r >> 1; + nbits --; + } + return res; + } + + computeVanishingPolinomial(bits, t) { + const m = 1 << bits; + return this.F.sub(this.F.pow(t, m), this.F.one); + } + + evaluateLagrangePolynomials(bits, t) { + const m= 1 << bits; + const tm = this.F.pow(t, m); + const u= new Array(m).fill(this.F.zero); + this._setRoots(bits); + const omega = this.w[bits]; + + if (this.F.eq(tm, this.F.one)) { + for (let i = 0; i < m; i++) { + if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i + u[i] = this.F.one; + return u; + } + } + } + + const z = this.F.sub(tm, this.F.one); + // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); + let l = this.F.mul(z, this.F.inv(this.F.e(m))); + for (let i = 0; i < m; i++) { + u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); + l = this.F.mul(l, omega); + } + + return u; + } + + log2(V) { + return log2(V); + } +} + +function log2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +} + + +function __fft(PF, pall, bits, offset, step) { + + const n = 1 << bits; + if (n==1) { + return [ pall[offset] ]; + } else if (n==2) { + return [ + PF.F.add(pall[offset], pall[offset + step]), + PF.F.sub(pall[offset], pall[offset + step])]; + } + + const ndiv2 = n >> 1; + const p1 = __fft(PF, pall, bits-1, offset, step*2); + const p2 = __fft(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> 1; + const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); + const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); + + const out = new Array(n); + + for (let i=0; i>=1; + } + return res; +} + +function rev(idx, bits) { + return ( + _revTable[idx >>> 24] | + (_revTable[(idx >>> 16) & 0xFF] << 8) | + (_revTable[(idx >>> 8) & 0xFF] << 16) | + (_revTable[idx & 0xFF] << 24) + ) >>> (32-bits); +} + +function __bitReverse(p, bits) { + for (let k=0; kk) { + const tmp= p[k]; + p[k] = p[r]; + p[r] = tmp; + } + } + +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/futils.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + + +function mulScalar(F, base, e) { + let res; + + if (Scalar.isZero(e)) return F.zero; + + const n = Scalar.naf(e); + + if (n[n.length-1] == 1) { + res = base; + } else if (n[n.length-1] == -1) { + res = F.neg(base); + } else { + throw new Error("invlaud NAF"); + } + + for (let i=n.length-2; i>=0; i--) { + + res = F.double(res); + + if (n[i] == 1) { + res = F.add(res, base); + } else if (n[i] == -1) { + res = F.sub(res, base); + } + } + + return res; +} + + +/* +exports.mulScalar = (F, base, e) =>{ + let res = F.zero; + let rem = bigInt(e); + let exp = base; + + while (! rem.eq(bigInt.zero)) { + if (rem.and(bigInt.one).eq(bigInt.one)) { + res = F.add(res, exp); + } + exp = F.double(exp); + rem = rem.shiftRight(1); + } + + return res; +}; +*/ + + +function futils_exp(F, base, e) { + + if (scalar_isZero(e)) return F.one; + + const n = scalar_bits(e); + + if (n.legth==0) return F.one; + + let res = base; + + for (let i=n.length-2; i>=0; i--) { + + res = F.square(res); + + if (n[i]) { + res = F.mul(res, base); + } + } + + return res; +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/fsqrt.js + +// Check here: https://eprint.iacr.org/2012/685.pdf + +function fsqrt_buildSqrt (F) { + if ((F.m % 2) == 1) { + if (scalar_eq(scalar_mod(F.p, 4), 1 )) { + if (scalar_eq(scalar_mod(F.p, 8), 1 )) { + if (scalar_eq(scalar_mod(F.p, 16), 1 )) { + // alg7_muller(F); + alg5_tonelliShanks(F); + } else if (scalar_eq(scalar_mod(F.p, 16), 9 )) { + alg4_kong(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (scalar_eq(scalar_mod(F.p, 8), 5 )) { + alg3_atkin(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (scalar_eq(scalar_mod(F.p, 4), 3 )) { + alg2_shanks(F); + } + } else { + const pm2mod4 = scalar_mod(scalar_pow(F.p, F.m/2), 4); + if (pm2mod4 == 1) { + alg10_adj(F); + } else if (pm2mod4 == 3) { + alg9_adj(F); + } else { + alg8_complex(F); + } + + } +} + + +function alg5_tonelliShanks(F) { + F.sqrt_q = scalar_pow(F.p, F.m); + + F.sqrt_s = 0; + F.sqrt_t = scalar_sub(F.sqrt_q, 1); + + while (!scalar_isOdd(F.sqrt_t)) { + F.sqrt_s = F.sqrt_s + 1; + F.sqrt_t = scalar_div(F.sqrt_t, 2); + } + + let c0 = F.one; + + while (F.eq(c0, F.one)) { + const c = F.random(); + F.sqrt_z = F.pow(c, F.sqrt_t); + c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); + } + + F.sqrt_tm1d2 = scalar_div(scalar_sub(F.sqrt_t, 1),2); + + F.sqrt = function(a) { + const F=this; + if (F.isZero(a)) return F.zero; + let w = F.pow(a, F.sqrt_tm1d2); + const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); + if (F.eq(a0, F.negone)) return null; + + let v = F.sqrt_s; + let x = F.mul(a, w); + let b = F.mul(x, w); + let z = F.sqrt_z; + while (!F.eq(b, F.one)) { + let b2k = F.square(b); + let k=1; + while (!F.eq(b2k, F.one)) { + b2k = F.square(b2k); + k++; + } + + w = z; + for (let i=0; i>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; + + st[a] = (st[a] + st[b]) >>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; +} + +function doubleRound(st) { + quarterRound(st, 0, 4, 8,12); + quarterRound(st, 1, 5, 9,13); + quarterRound(st, 2, 6,10,14); + quarterRound(st, 3, 7,11,15); + + quarterRound(st, 0, 5,10,15); + quarterRound(st, 1, 6,11,12); + quarterRound(st, 2, 7, 8,13); + quarterRound(st, 3, 4, 9,14); +} + +class ChaCha { + + constructor(seed) { + seed = seed || [0,0,0,0,0,0,0,0]; + this.state = [ + 0x61707865, + 0x3320646E, + 0x79622D32, + 0x6B206574, + seed[0], + seed[1], + seed[2], + seed[3], + seed[4], + seed[5], + seed[6], + seed[7], + 0, + 0, + 0, + 0 + ]; + this.idx = 16; + this.buff = new Array(16); + } + + nextU32() { + if (this.idx == 16) this.update(); + return this.buff[this.idx++]; + } + + nextU64() { + return scalar_add(scalar_mul(this.nextU32(), 0x100000000), this.nextU32()); + } + + nextBool() { + return (this.nextU32() & 1) == 1; + } + + update() { + // Copy the state + for (let i=0; i<16; i++) this.buff[i] = this.state[i]; + + // Apply the rounds + for (let i=0; i<10; i++) doubleRound(this.buff); + + // Add to the initial + for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; + + this.idx = 0; + + this.state[12] = (this.state[12] + 1) >>> 0; + if (this.state[12] != 0) return; + this.state[13] = (this.state[13] + 1) >>> 0; + if (this.state[13] != 0) return; + this.state[14] = (this.state[14] + 1) >>> 0; + if (this.state[14] != 0) return; + this.state[15] = (this.state[15] + 1) >>> 0; + } +} + +// EXTERNAL MODULE: ./node_modules/crypto-browserify/index.js +var crypto_browserify = __webpack_require__(91565); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/random.js +/* provided dependency */ var process = __webpack_require__(65606); + + + +function getRandomBytes(n) { + let array = new Uint8Array(n); + if (process.browser) { // Browser + if (typeof globalThis.crypto !== "undefined") { // Supported + globalThis.crypto.getRandomValues(array); + } else { // fallback + for (let i=0; i>>0; + } + } + } + else { // NodeJS + crypto_browserify.randomFillSync(array); + } + return array; +} + +function getRandomSeed() { + const arr = getRandomBytes(32); + const arrV = new Uint32Array(arr.buffer); + const seed = []; + for (let i=0; i<8; i++) { + seed.push(arrV[i]); + } + return seed; +} + +let threadRng = null; + +function getThreadRng() { + if (threadRng) return threadRng; + threadRng = new ChaCha(getRandomSeed()); + return threadRng; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_native.js +/* global BigInt */ + + + + + +class ZqField { + constructor(p) { + this.type="F1"; + this.one = BigInt(1); + this.zero = BigInt(0); + this.p = BigInt(p); + this.m = 1; + this.negone = this.p-this.one; + this.two = BigInt(2); + this.half = this.p >> this.one; + this.bitLength = scalar_bitLength(this.p); + this.mask = (this.one << BigInt(this.bitLength)) - this.one; + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = this.e(this.one << BigInt(this.n64*64)); + this.Ri = this.inv(this.R); + + const e = this.negone >> this.one; + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!this.eq(r, this.negone)) { + this.nqr = this.nqr + this.one; + r = this.pow(this.nqr, e); + } + + + this.s = 0; + this.t = this.negone; + + while ((this.t & this.one) == this.zero) { + this.s = this.s + 1; + this.t = this.t >> this.one; + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + fsqrt_buildSqrt(this); + } + + e(a,b) { + let res; + if (!b) { + res = BigInt(a); + } else if (b==16) { + res = BigInt("0x"+a); + } + if (res < 0) { + let nres = -res; + if (nres >= this.p) nres = nres % this.p; + return this.p - nres; + } else { + return (res>= this.p) ? res%this.p : res; + } + + } + + add(a, b) { + const res = a + b; + return res >= this.p ? res-this.p : res; + } + + sub(a, b) { + return (a >= b) ? a-b : this.p-b+a; + } + + neg(a) { + return a ? this.p-a : a; + } + + mul(a, b) { + return (a*b)%this.p; + } + + mulScalar(base, s) { + return (base * this.e(s)) % this.p; + } + + square(a) { + return (a*a) % this.p; + } + + eq(a, b) { + return a==b; + } + + neq(a, b) { + return a!=b; + } + + lt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa < bb; + } + + gt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa > bb; + } + + leq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa <= bb; + } + + geq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa >= bb; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + idiv(a, b) { + if (!b) throw new Error("Division by zero"); + return a / b; + } + + inv(a) { + if (!a) throw new Error("Division by zero"); + + let t = this.zero; + let r = this.p; + let newt = this.one; + let newr = a % this.p; + while (newr) { + let q = r/newr; + [t, newt] = [newt, t-q*newt]; + [r, newr] = [newr, r-q*newr]; + } + if (t= this.p ? res-this.p : res; + } + + bor(a, b) { + const res = ((a | b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bxor(a, b) { + const res = ((a ^ b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bnot(a) { + const res = a ^ this.mask; + return res >= this.p ? res-this.p : res; + } + + shl(a, b) { + if (Number(b) < this.bitLength) { + const res = (a << b) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + return a >> nb; + } else { + return this.zero; + } + } + } + + shr(a, b) { + if (Number(b) < this.bitLength) { + return a >> b; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + const res = (a << nb) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + return 0; + } + } + } + + land(a, b) { + return (a && b) ? this.one : this.zero; + } + + lor(a, b) { + return (a || b) ? this.one : this.zero; + } + + lnot(a) { + return (a) ? this.zero : this.one; + } + + sqrt_old(n) { + + if (n == this.zero) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone >> this.one); + if ( res != this.one ) return null; + + let m = this.s; + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one) >> this.one ); + + while ( t != this.one ) { + let sq = this.square(t); + let i = 1; + while (sq != this.one ) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r > (this.p >> this.one)) { + r = this.neg(r); + } + + return r; + } + + normalize(a, b) { + a = BigInt(a,b); + if (a < 0) { + let na = -a; + if (na >= this.p) na = na % this.p; + return this.p - na; + } else { + return (a>= this.p) ? a%this.p : a; + } + } + + random() { + const nBytes = (this.bitLength*2 / 8); + let res =this.zero; + for (let i=0; i this.half) { + const v = this.p-a; + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + return vs; + } + + isZero(a) { + return a == this.zero; + } + + fromRng(rng) { + let v; + do { + v=this.zero; + for (let i=0; i= this.p); + v = (v * this.Ri) % this.p; // Convert from montgomery + return v; + } + +} + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_bigint.js + + + + +class f1field_bigint_ZqField { + constructor(p) { + this.type="F1"; + this.one = BigInteger.one; + this.zero = BigInteger.zero; + this.p = BigInteger(p); + this.m = 1; + this.negone = this.p.minus(BigInteger.one); + this.two = BigInteger(2); + this.half = this.p.shiftRight(1); + this.bitLength = this.p.bitLength(); + this.mask = BigInteger.one.shiftLeft(this.bitLength).minus(BigInteger.one); + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = BigInteger.one.shiftLeft(this.n64*64); + this.Ri = this.inv(this.R); + + const e = this.negone.shiftRight(this.one); + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!r.equals(this.negone)) { + this.nqr = this.nqr.add(this.one); + r = this.pow(this.nqr, e); + } + + this.s = this.zero; + this.t = this.negone; + + while (!this.t.isOdd()) { + this.s = this.s.add(this.one); + this.t = this.t.shiftRight(this.one); + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + fsqrt_buildSqrt(this); + } + + e(a,b) { + + const res = BigInteger(a,b); + + return this.normalize(res); + + } + + add(a, b) { + let res = a.add(b); + if (res.geq(this.p)) { + res = res.minus(this.p); + } + return res; + } + + sub(a, b) { + if (a.geq(b)) { + return a.minus(b); + } else { + return this.p.minus(b.minus(a)); + } + } + + neg(a) { + if (a.isZero()) return a; + return this.p.minus(a); + } + + mul(a, b) { + return a.times(b).mod(this.p); + } + + mulScalar(base, s) { + return base.times(BigInteger(s)).mod(this.p); + } + + square(a) { + return a.square().mod(this.p); + } + + eq(a, b) { + return a.eq(b); + } + + neq(a, b) { + return a.neq(b); + } + + lt(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.lt(bb); + } + + gt(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.gt(bb); + } + + leq(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.leq(bb); + } + + geq(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.geq(bb); + } + + div(a, b) { + if (b.isZero()) throw new Error("Division by zero"); + return a.times(b.modInv(this.p)).mod(this.p); + } + + idiv(a, b) { + if (b.isZero()) throw new Error("Division by zero"); + return a.divide(b); + } + + inv(a) { + if (a.isZero()) throw new Error("Division by zero"); + return a.modInv(this.p); + } + + mod(a, b) { + return a.mod(b); + } + + pow(a, b) { + return a.modPow(b, this.p); + } + + exp(a, b) { + return a.modPow(b, this.p); + } + + band(a, b) { + return a.and(b).and(this.mask).mod(this.p); + } + + bor(a, b) { + return a.or(b).and(this.mask).mod(this.p); + } + + bxor(a, b) { + return a.xor(b).and(this.mask).mod(this.p); + } + + bnot(a) { + return a.xor(this.mask).mod(this.p); + } + + shl(a, b) { + if (b.lt(this.bitLength)) { + return a.shiftLeft(b).and(this.mask).mod(this.p); + } else { + const nb = this.p.minus(b); + if (nb.lt(this.bitLength)) { + return this.shr(a, nb); + } else { + return BigInteger.zero; + } + } + } + + shr(a, b) { + if (b.lt(this.bitLength)) { + return a.shiftRight(b); + } else { + const nb = this.p.minus(b); + if (nb.lt(this.bitLength)) { + return this.shl(a, nb); + } else { + return BigInteger.zero; + } + } + } + + land(a, b) { + return (a.isZero() || b.isZero()) ? BigInteger.zero : BigInteger.one; + } + + lor(a, b) { + return (a.isZero() && b.isZero()) ? BigInteger.zero : BigInteger.one; + } + + lnot(a) { + return a.isZero() ? BigInteger.one : BigInteger.zero; + } + + sqrt_old(n) { + + if (n.equals(this.zero)) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone.shiftRight(this.one)); + if (!res.equals(this.one)) return null; + + let m = parseInt(this.s); + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) ); + + while (!t.equals(this.one)) { + let sq = this.square(t); + let i = 1; + while (!sq.equals(this.one)) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r.greater(this.p.shiftRight(this.one))) { + r = this.neg(r); + } + + return r; + } + + normalize(a) { + a = BigInteger(a); + if (a.isNegative()) { + return this.p.minus(a.abs().mod(this.p)); + } else { + return a.mod(this.p); + } + } + + random() { + let res = BigInteger(0); + let n = BigInteger(this.p.square()); + while (!n.isZero()) { + res = res.shiftLeft(8).add(BigInteger(getRandomBytes(1)[0])); + n = n.shiftRight(8); + } + return res.mod(this.p); + } + + toString(a, base) { + let vs; + if (!a.lesserOrEquals(this.p.shiftRight(BigInteger(1)))) { + const v = this.p.minus(a); + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + + return vs; + } + + isZero(a) { + return a.isZero(); + } + + fromRng(rng) { + let v; + do { + v = BigInteger(0); + for (let i=0; i. +*/ + + + + +class F2Field { + constructor(F, nonResidue) { + this.type="F2"; + this.F = F; + this.zero = [this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*2; + this.p = F.p; + this.n64 = F.n64*2; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + + buildSqrt(this); + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + conjugate(a) { + return [ + a[0], + this.F.neg(a[1]) + ]; + } + + mul(a, b) { + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + + return [ + this.F.add( aA , this._mulByNonResidue(bB)), + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB))]; + } + + inv(a) { + const t0 = this.F.square(a[0]); + const t1 = this.F.square(a[1]); + const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); + const t3 = this.F.inv(t2); + return [ + this.F.mul(a[0], t3), + this.F.neg(this.F.mul( a[1], t3)) ]; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const ab = this.F.mul(a[0] , a[1]); + + /* + [ + (a + b) * (a + non_residue * b) - ab - non_residue * ab, + ab + ab + ]; + */ + + return [ + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]) , + this.F.add( + a[0] , + this._mulByNonResidue(a[1]))), + this.F.add( + ab, + this._mulByNonResidue(ab))), + this.F.add(ab, ab) + ]; + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + pow(base, e) { + return fUtils.exp(this, base, e); + } + + exp(base, e) { + return fUtils.exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + return [c0, c1]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + return false; + } + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[1]); + this.F.toRprBE(buff, o+this.F.n8, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[1]); + this.F.toRprBEM(buff, o+this.F.n8, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBE(buff, o); + const c0 = this.F.fromRprBE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBEM(buff, o); + const c0 = this.F.fromRprBEM(buff, o+this.F.n8); + return [c0, c1]; + } + +} + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f3field.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + +class F3Field { + constructor(F, nonResidue) { + this.type="F3"; + this.F = F; + this.zero = [this.F.zero, this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*3; + this.p = F.p; + this.n64 = F.n64*3; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]), + this.F.add(a[2], b[2]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]), + this.F.sub(a[2], b[2]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + mul(a, b) { + + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + const cC = this.F.mul(a[2] , b[2]); + + return [ + this.F.add( + aA, + this._mulByNonResidue( + this.F.sub( + this.F.mul( + this.F.add(a[1], a[2]), + this.F.add(b[1], b[2])), + this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB)), + this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[2]), + this.F.add(b[0], b[2])), + this.F.add(aA, cC)), + bB)]; // (a+c)*(A+C)-aA+bB-cC) + } + + inv(a) { + const t0 = this.F.square(a[0]); // t0 = a^2 ; + const t1 = this.F.square(a[1]); // t1 = b^2 ; + const t2 = this.F.square(a[2]); // t2 = c^2; + const t3 = this.F.mul(a[0],a[1]); // t3 = ab + const t4 = this.F.mul(a[0],a[2]); // t4 = ac + const t5 = this.F.mul(a[1],a[2]); // t5 = bc; + // c0 = t0 - non_residue * t5; + const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); + // c1 = non_residue * t2 - t3; + const c1 = this.F.sub(this._mulByNonResidue(t2), t3); + const c2 = this.F.sub(t1, t4); // c2 = t1-t4 + + // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); + const t6 = + this.F.inv( + this.F.add( + this.F.mul(a[0], c0), + this._mulByNonResidue( + this.F.add( + this.F.mul(a[2], c1), + this.F.mul(a[1], c2))))); + + return [ + this.F.mul(t6, c0), // t6*c0 + this.F.mul(t6, c1), // t6*c1 + this.F.mul(t6, c2)]; // t6*c2 + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const s0 = this.F.square(a[0]); // s0 = a^2 + const ab = this.F.mul(a[0], a[1]); // ab = a*b + const s1 = this.F.add(ab, ab); // s1 = 2ab; + const s2 = this.F.square( + this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; + const bc = this.F.mul(a[1],a[2]); // bc = b*c + const s3 = this.F.add(bc, bc); // s3 = 2*bc + const s4 = this.F.square(a[2]); // s4 = c^2 + + + return [ + this.F.add( + s0, + this._mulByNonResidue(s3)), // s0 + non_residue * s3, + this.F.add( + s1, + this._mulByNonResidue(s4)), // s1 + non_residue * s4, + this.F.sub( + this.F.add( this.F.add(s1, s2) , s3 ), + this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); + } + + affine(a) { + return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + pow(base, e) { + return fUtils.exp(this, base, e); + } + + exp(base, e) { + return fUtils.exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + const c2 = this.F.fromRng(rng); + return [c0, c1, c2]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + if (this.F.gt(b[1], a[1])) return false; + if (this.F.gt(a[2], b[2])) return true; + return false; + } + + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + this.F.toRprLE(buff, o+this.F.n8*2, e[2]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[2]); + this.F.toRprBE(buff, o+this.F.n8, e[1]); + this.F.toRprBE(buff, o+this.F.n8*2, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[2]); + this.F.toRprBEM(buff, o+this.F.n8, e[1]); + this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.n8); + const c2 = this.F.fromRprLE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBE(buff, o); + const c1 = this.F.fromRprBE(buff, o+this.n8); + const c0 = this.F.fromRprBE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.n8); + const c2 = this.F.fromRprLEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBEM(buff, o); + const c1 = this.F.fromRprBEM(buff, o+this.n8); + const c0 = this.F.fromRprBEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/ec.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + + + + + +function isGreatest(F, a) { + if (Array.isArray(a)) { + for (let i=a.length-1; i>=0; i--) { + if (!F.F.isZero(a[i])) { + return isGreatest(F.F, a[i]); + } + } + return 0; + } else { + const na = F.neg(a); + return Scalar.gt(a, na); + } +} + + +class EC { + + constructor(F, g) { + this.F = F; + this.g = g; + if (this.g.length == 2) this.g[2] = this.F.one; + this.zero = [this.F.zero, this.F.one, this.F.zero]; + } + + add(p1, p2) { + + const F = this.F; + + if (this.eq(p1, this.zero)) return p2; + if (this.eq(p2, this.zero)) return p1; + + const res = new Array(3); + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 + const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 + const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 + + if (F.eq(U1,U2) && F.eq(S1,S2)) { + return this.double(p1); + } + + const H = F.sub( U2 , U1 ); // H = U2-U1 + + const S2_minus_S1 = F.sub( S2 , S1 ); + + const I = F.square( F.add(H,H) ); // I = (2 * H)^2 + const J = F.mul( H , I ); // J = H * I + + const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) + const V = F.mul( U1 , I ); // V = U1 * I + + res[0] = + F.sub( + F.sub( F.square(r) , J ), + F.add( V , V )); // X3 = r^2 - J - 2 * V + + const S1_J = F.mul( S1 , J ); + + res[1] = + F.sub( + F.mul( r , F.sub(V,res[0])), + F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J + + res[2] = + F.mul( + H, + F.sub( + F.square( F.add(p1[2],p2[2]) ), + F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H + + return res; + } + + neg(p) { + return [p[0], this.F.neg(p[1]), p[2]]; + } + + sub(a, b) { + return this.add(a, this.neg(b)); + } + + double(p) { + const F = this.F; + + const res = new Array(3); + + if (this.eq(p, this.zero)) return p; + + const A = F.square( p[0] ); // A = X1^2 + const B = F.square( p[1] ); // B = Y1^2 + const C = F.square( B ); // C = B^2 + + let D = + F.sub( + F.square( F.add(p[0] , B )), + F.add( A , C)); + D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) + + const E = F.add( F.add(A,A), A); // E = 3 * A + const FF =F.square( E ); // F = E^2 + + res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D + + let eightC = F.add( C , C ); + eightC = F.add( eightC , eightC ); + eightC = F.add( eightC , eightC ); + + res[1] = + F.sub( + F.mul( + E, + F.sub( D, res[0] )), + eightC); // Y3 = E * (D - X3) - 8 * C + + const Y1Z1 = F.mul( p[1] , p[2] ); + res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 + + return res; + } + + timesScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + affine(p) { + const F = this.F; + if (this.isZero(p)) { + return this.zero; + } else if (F.eq(p[2], F.one)) { + return p; + } else { + const Z_inv = F.inv(p[2]); + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + const res = new Array(3); + res[0] = F.mul(p[0],Z2_inv); + res[1] = F.mul(p[1],Z3_inv); + res[2] = F.one; + + return res; + } + } + + multiAffine(arr) { + const keys = Object.keys(arr); + const F = this.F; + const accMul = new Array(keys.length+1); + accMul[0] = F.one; + for (let i = 0; i< keys.length; i++) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i+1] = accMul[i]; + } else { + accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); + } + } + + accMul[keys.length] = F.inv(accMul[keys.length]); + + for (let i = keys.length-1; i>=0; i--) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i] = accMul[i+1]; + arr[keys[i]] = this.zero; + } else { + const Z_inv = F.mul(accMul[i], accMul[i+1]); + accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); + + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); + arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); + arr[keys[i]][2] = F.one; + } + } + + } + + eq(p1, p2) { + const F = this.F; + + if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); + if (this.F.eq(p2[2], this.F.zero)) return false; + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); + const U2 = F.mul( p2[0] , Z1Z1 ); + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); + const S2 = F.mul( p2[1] , Z1_cubed); + + return (F.eq(U1,U2) && F.eq(S1,S2)); + } + + isZero(p) { + return this.F.isZero(p[2]); + } + + toString(p) { + const cp = this.affine(p); + return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; + } + + fromRng(rng) { + const F = this.F; + let P = []; + let greatest; + do { + P[0] = F.fromRng(rng); + greatest = rng.nextBool(); + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + } while ((P[1] == null)||(F.isZero[P])); + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + if (this.cofactor) { + P = this.mulScalar(P, this.cofactor); + } + + P = this.affine(P); + + return P; + + } + + toRprLE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLE(buff, o, p[0]); + this.F.toRprLE(buff, o+this.F.n8, p[1]); + } + + toRprBE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBE(buff, o, p[0]); + this.F.toRprBE(buff, o+this.F.n8, p[1]); + } + + toRprLEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + } + + toRprLEJM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); + } + + + toRprBEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBEM(buff, o, p[0]); + this.F.toRprBEM(buff, o+this.F.n8, p[1]); + } + + fromRprLE(buff, o) { + o = o || 0; + const x = this.F.fromRprLE(buff, o); + const y = this.F.fromRprLE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprBE(buff, o) { + o = o || 0; + const x = this.F.fromRprBE(buff, o); + const y = this.F.fromRprBE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEJM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + const z = this.F.fromRprLEM(buff, o+this.F.n8*2); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, z]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const x = this.F.fromRprBEM(buff, o); + const y = this.F.fromRprBEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprCompressed(buff, o) { + const F = this.F; + const v = new Uint8Array(buff.buffer, o, F.n8); + if (v[0] & 0x40) return this.zero; + const P = new Array(3); + + const greatest = ((v[0] & 0x80) != 0); + v[0] = v[0] & 0x7F; + P[0] = F.fromRprBE(buff, o); + if (greatest) v[0] = v[0] | 0x80; // set back again the old value + + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + + if (P[1] === null) { + throw new Error("Invalid Point!"); + } + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + return P; + } + + toRprCompressed(buff, o, p) { + p = this.affine(p); + const v = new Uint8Array(buff.buffer, o, this.F.n8); + if (this.isZero(p)) { + v.fill(0); + v[0] = 0x40; + return; + } + this.F.toRprBE(buff, o, p[0]); + + if (isGreatest(this.F, p[1])) { + v[0] = v[0] | 0x80; + } + } + + + fromRprUncompressed(buff, o) { + if (buff[0] & 0x40) return this.zero; + + return this.fromRprBE(buff, o); + } + + toRprUncompressed(buff, o, p) { + this.toRprBE(buff, o, p); + + if (this.isZero(p)) { + buff[o] = buff[o] | 0x40; + } + } + + +} + + + +// EXTERNAL MODULE: ./node_modules/wasmcurves/index.js +var wasmcurves = __webpack_require__(70189); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_native.js +/* global BigInt */ + + +function stringifyBigInts(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return fromRprLE(o, 0); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return BigInt(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return BigInt(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function beBuff2int(buff) { + let res = BigInt(0); + let i = buff.length; + let offset = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i>0) { + if (i >= 4) { + i -= 4; + res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); + offset += 4; + } else if (i >= 2) { + i -= 2; + res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); + offset += 2; + } else { + i -= 1; + res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); + offset += 1; + } + } + return res; +} + +function beInt2Buff(n, len) { + let r = n; + const buff = new Uint8Array(len); + const buffV = new DataView(buff.buffer); + let o = len; + while (o > 0) { + if (o-4 >= 0) { + o -= 4; + buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); + r = r >> BigInt(32); + } else if (o-2 >= 0) { + o -= 2; + buffV.setUint16(o, Number(r & BigInt(0xFFFF))); + r = r >> BigInt(16); + } else { + o -= 1; + buffV.setUint8(o, Number(r & BigInt(0xFF))); + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function leBuff2int(buff) { + let res = BigInt(0); + let i = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i> BigInt(32); + } else if (o+2 <= len) { + buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); + o += 2; + r = r >> BigInt(16); + } else { + buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); + o += 1; + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function stringifyFElements(F, o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return F.toString(F.e(o)); + } else if (Array.isArray(o)) { + return o.map(stringifyFElements.bind(this,F)); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyFElements(F, o[k]); + }); + return res; + } else { + return o; + } +} + + +function unstringifyFElements(F, o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return F.e(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return F.e(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyFElements.bind(this,F)); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyFElements(F, o[k]); + }); + return res; + } else { + return o; + } +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_bigint.js + + +function utils_bigint_stringifyBigInts(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (Array.isArray(o)) { + return o.map(utils_bigint_stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = utils_bigint_stringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function utils_bigint_unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return BigInteger(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return BigInteger(o); + } else if (Array.isArray(o)) { + return o.map(utils_bigint_unstringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = utils_bigint_unstringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function utils_bigint_beBuff2int(buff) { + let res = BigInteger.zero; + for (let i=0; i=0)) { + let c = Number(r.and(BigInteger("255"))); + buff[o] = c; + o--; + r = r.shiftRight(8); + } + if (!r.eq(BigInteger.zero)) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function utils_bigint_leBuff2int (buff) { + let res = BigInteger.zero; + for (let i=0; i>=1; + } + return res; +} + +utils.bitReverse = function bitReverse(idx, bits) { + return ( + utils_revTable[idx >>> 24] | + (utils_revTable[(idx >>> 16) & 0xFF] << 8) | + (utils_revTable[(idx >>> 8) & 0xFF] << 16) | + (utils_revTable[idx & 0xFF] << 24) + ) >>> (32-bits); +}; + + +utils.log2 = function log2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +}; + +utils.buffReverseBits = function buffReverseBits(buff, eSize) { + const n = buff.byteLength /eSize; + const bits = utils.log2(n); + if (n != (1 << bits)) { + throw new Error("Invalid number of pointers"); + } + for (let i=0; ir) { + const tmp = buff.slice(i*eSize, (i+1)*eSize); + buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); + buff.set(tmp, r*eSize); + } + } +}; + + +utils.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i0) { + // bytes to copy from this page + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset+o, l); + if (l == len) return srcView.slice(); + if (!buff) { + if (len <= PAGE_SIZE) { + buff = new Uint8Array(len); + } else { + buff = new BigBuffer(len); + } + } + buff.set(srcView, len-r); + r = r-l; + p ++; + o = 0; + } + + return buff; + } + + set(buff, offset) { + if (offset === undefined) offset = 0; + + const len = buff.byteLength; + + if (len==0) return; + + const firstPage = Math.floor(offset / PAGE_SIZE); + const lastPage = Math.floor((offset+len-1) / PAGE_SIZE); + + if (firstPage == lastPage) { + if ((buff instanceof BigBuffer)&&(buff.buffers.length==1)) { + return this.buffers[firstPage].set(buff.buffers[0], offset % PAGE_SIZE); + } else { + return this.buffers[firstPage].set(buff, offset % PAGE_SIZE); + } + + } + + + let p = firstPage; + let o = offset % PAGE_SIZE; + let r = len; + while (r>0) { + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = buff.slice( len -r, len -r+l); + const dstView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset + o, l); + dstView.set(srcView); + r = r-l; + p ++; + o = 0; + } + + } +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine_batchconvert.js + + +function buildBatchConvert(tm, fnName, sIn, sOut) { + return async function batchConvert(buffIn) { + const nPoints = Math.floor(buffIn.byteLength / sIn); + if ( nPoints * sIn !== buffIn.byteLength) { + throw new Error("Invalid buffer size"); + } + const pointsPerChunk = Math.floor(nPoints/tm.concurrency); + const opPromises = []; + for (let i=0; i=0; i--) { + this.w[i] = this.square(this.w[i+1]); + } + + if (!this.eq(this.w[0], this.one)) { + throw new Error("Error calculating roots of unity"); + } + + this.batchToMontgomery = buildBatchConvert(tm, prefix + "_batchToMontgomery", this.n8, this.n8); + this.batchFromMontgomery = buildBatchConvert(tm, prefix + "_batchFromMontgomery", this.n8, this.n8); + } + + + op2(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op2Bool(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2); + } + + op1(opName, a) { + this.tm.setBuff(this.pOp1, a); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op1Bool(opName, a) { + this.tm.setBuff(this.pOp1, a); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + } + + add(a,b) { + return this.op2("_add", a, b); + } + + + eq(a,b) { + return this.op2Bool("_eq", a, b); + } + + isZero(a) { + return this.op1Bool("_isZero", a); + } + + sub(a,b) { + return this.op2("_sub", a, b); + } + + neg(a) { + return this.op1("_neg", a); + } + + inv(a) { + return this.op1("_inverse", a); + } + + toMontgomery(a) { + return this.op1("_toMontgomery", a); + } + + fromMontgomery(a) { + return this.op1("_fromMontgomery", a); + } + + mul(a,b) { + return this.op2("_mul", a, b); + } + + div(a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_inverse"](this.pOp2, this.pOp2); + this.tm.instance.exports[this.prefix + "_mul"](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + square(a) { + return this.op1("_square", a); + } + + isSquare(a) { + return this.op1Bool("_isSquare", a); + } + + sqrt(a) { + return this.op1("_sqrt", a); + } + + exp(a, b) { + if (!(b instanceof Uint8Array)) { + b = toLEBuff(scalar_e(b)); + } + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_exp"](this.pOp1, this.pOp2, b.byteLength, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + isNegative(a) { + return this.op1Bool("_isNegative", a); + } + + e(a, b) { + if (a instanceof Uint8Array) return a; + let ra = scalar_e(a, b); + if (scalar_isNegative(ra)) { + ra = scalar_neg(ra); + if (scalar_gt(ra, this.p)) { + ra = scalar_mod(ra, this.p); + } + ra = scalar_sub(this.p, ra); + } else { + if (scalar_gt(ra, this.p)) { + ra = scalar_mod(ra, this.p); + } + } + const buff = utils_leInt2Buff(ra, this.n8); + return this.toMontgomery(buff); + } + + toString(a, radix) { + const an = this.fromMontgomery(a); + const s = fromRprLE(an, 0); + return scalar_toString(s, radix); + } + + fromRng(rng) { + let v; + const buff = new Uint8Array(this.n8); + do { + v = zero; + for (let i=0; i memory.buffer.byteLength) { + const currentPages = memory.buffer.byteLength / 0x10000; + let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1; + if (requiredPages>MAXMEM) requiredPages=MAXMEM; + memory.grow(requiredPages-currentPages); + } + return res; + } + + function allocBuffer(buffer) { + const p = alloc(buffer.byteLength); + setBuffer(p, buffer); + return p; + } + + function getBuffer(pointer, length) { + const u8 = new Uint8Array(memory.buffer); + return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length); + } + + function setBuffer(pointer, buffer) { + const u8 = new Uint8Array(memory.buffer); + u8.set(new Uint8Array(buffer), pointer); + } + + function runTask(task) { + if (task[0].cmd == "INIT") { + return init(task[0]); + } + const ctx = { + vars: [], + out: [] + }; + const u32a = new Uint32Array(memory.buffer, 0, 1); + const oldAlloc = u32a[0]; + for (let i=0; i. +*/ + +// const MEM_SIZE = 1000; // Memory size in 64K Pakes (512Mb) +const MEM_SIZE = 25; // Memory size in 64K Pakes (1600Kb) + + + + + + +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject)=> { + this.reject = reject; + this.resolve = resolve; + }); + } +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function stringToBase64(str) { + if (threadman_process.browser) { + return globalThis.btoa(str); + } else { + return Buffer.from(str).toString("base64"); + } +} + +const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); +const workerSource = "data:application/javascript;base64," + threadSource; + + + +async function buildThreadManager(wasm, singleThread) { + const tm = new ThreadManager(); + + tm.memory = new WebAssembly.Memory({initial:MEM_SIZE}); + tm.u8 = new Uint8Array(tm.memory.buffer); + tm.u32 = new Uint32Array(tm.memory.buffer); + + const wasmModule = await WebAssembly.compile(wasm.code); + + tm.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": tm.memory + } + }); + + tm.singleThread = singleThread; + tm.initalPFree = tm.u32[0]; // Save the Pointer to free space. + tm.pq = wasm.pq; + tm.pr = wasm.pr; + tm.pG1gen = wasm.pG1gen; + tm.pG1zero = wasm.pG1zero; + tm.pG2gen = wasm.pG2gen; + tm.pG2zero = wasm.pG2zero; + tm.pOneT = wasm.pOneT; + + // tm.pTmp0 = tm.alloc(curve.G2.F.n8*3); + // tm.pTmp1 = tm.alloc(curve.G2.F.n8*3); + + + if (singleThread) { + tm.code = wasm.code; + tm.taskManager = thread(); + await tm.taskManager([{ + cmd: "INIT", + init: MEM_SIZE, + code: tm.code.slice() + }]); + tm.concurrency = 1; + } else { + tm.workers = []; + tm.pendingDeferreds = []; + tm.working = []; + + let concurrency; + + if ((typeof(navigator) === "object") && navigator.hardwareConcurrency) { + concurrency = navigator.hardwareConcurrency; + } else { + concurrency = browser.cpus().length; + } + + if(concurrency == 0){ + concurrency = 2; + } + + // Limit to 64 threads for memory reasons. + if (concurrency>64) concurrency=64; + tm.concurrency = concurrency; + + for (let i = 0; i 0); i++) { + if (this.working[i] == false) { + const work = this.actionQueue.shift(); + this.postAction(i, work.data, work.transfers, work.deferred); + } + } + } + + queueAction(actionData, transfers) { + const d = new Deferred(); + + if (this.singleThread) { + const res = this.taskManager(actionData); + d.resolve(res); + } else { + this.actionQueue.push({ + data: actionData, + transfers: transfers, + deferred: d + }); + this.processWorks(); + } + return d.promise; + } + + resetMemory() { + this.u32[0] = this.initalPFree; + } + + allocBuff(buff) { + const pointer = this.alloc(buff.byteLength); + this.setBuff(pointer, buff); + return pointer; + } + + getBuff(pointer, length) { + return this.u8.slice(pointer, pointer+ length); + } + + setBuff(pointer, buffer) { + this.u8.set(new Uint8Array(buffer), pointer); + } + + alloc(length) { + while (this.u32[0] & 3) this.u32[0]++; // Return always aligned pointers + const res = this.u32[0]; + this.u32[0] += length; + return res; + } + + async terminate() { + for (let i=0; i=0; i--) { + if (!G.isZero(res)) { + for (let j=0; jMAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + if (chunkSize { + if (logger) logger.debug(`Multiexp end: ${logText}: ${i}/${nPoints}`); + return r; + })); + } + + const result = await Promise.all(opPromises); + + let res = G.zero; + for (let i=result.length-1; i>=0; i--) { + res = G.add(res, result[i]); + } + + return res; + } + + G.multiExp = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "jacobian", logger, logText); + }; + G.multiExpAffine = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "affine", logger, logText); + }; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine_fft.js + + + + +function buildFFT(curve, groupName) { + const G = curve[groupName]; + const Fr = curve.Fr; + const tm = G.tm; + async function _fft(buff, inverse, inType, outType, logger, loggerTxt) { + + inType = inType || "affine"; + outType = outType || "affine"; + const MAX_BITS_THREAD = 14; + + let sIn, sMid, sOut, fnIn2Mid, fnMid2Out, fnFFTMix, fnFFTJoin, fnFFTFinal; + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g1m_fftFinal"; + } + fnFFTJoin = "g1m_fftJoin"; + fnFFTMix = "g1m_fftMix"; + + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g1m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g2m_fftFinal"; + } + fnFFTJoin = "g2m_fftJoin"; + fnFFTMix = "g2m_fftMix"; + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g2m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = G.n8; + sMid = G.n8; + sOut = G.n8; + if (inverse) { + fnFFTFinal = "frm_fftFinal"; + } + fnFFTMix = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } + + + let returnArray = false; + if (Array.isArray(buff)) { + buff = array2buffer(buff, sIn); + returnArray = true; + } else { + buff = buff.slice(0, buff.byteLength); + } + + const nPoints = buff.byteLength / sIn; + const bits = utils_log2(nPoints); + + if ((1 << bits) != nPoints) { + throw new Error("fft must be multiple of 2" ); + } + + if (bits == Fr.s +1) { + let buffOut; + + if (inverse) { + buffOut = await _fftExtInv(buff, inType, outType, logger, loggerTxt); + } else { + buffOut = await _fftExt(buff, inType, outType, logger, loggerTxt); + } + + if (returnArray) { + return buffer2array(buffOut, sOut); + } else { + return buffOut; + } + } + + let inv; + if (inverse) { + inv = Fr.inv(Fr.e(nPoints)); + } + + let buffOut; + + buffReverseBits(buff, sIn); + + let chunks; + let pointsInChunk = Math.min(1 << MAX_BITS_THREAD, nPoints); + let nChunks = nPoints / pointsInChunk; + + while ((nChunks < tm.concurrency)&&(pointsInChunk>=16)) { + nChunks *= 2; + pointsInChunk /= 2; + } + + const l2Chunk = utils_log2(pointsInChunk); + + const promises = []; + for (let i = 0; i< nChunks; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix start: ${i}/${nChunks}`); + const task = []; + task.push({cmd: "ALLOC", var: 0, len: sMid*pointsInChunk}); + const buffChunk = buff.slice( (pointsInChunk * i)*sIn, (pointsInChunk * (i+1))*sIn); + task.push({cmd: "SET", var: 0, buff: buffChunk}); + if (fnIn2Mid) { + task.push({cmd: "CALL", fnName:fnIn2Mid, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + for (let j=1; j<=l2Chunk;j++) { + task.push({cmd: "CALL", fnName:fnFFTMix, params: [{var:0}, {val: pointsInChunk}, {val: j}]}); + } + + if (l2Chunk==bits) { + if (fnFFTFinal) { + task.push({cmd: "ALLOCSET", var: 1, buff: inv}); + task.push({cmd: "CALL", fnName: fnFFTFinal, params:[ + {var: 0}, + {val: pointsInChunk}, + {var: 1}, + ]}); + } + if (fnMid2Out) { + task.push({cmd: "CALL", fnName:fnMid2Out, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + task.push({cmd: "GET", out: 0, var: 0, len: pointsInChunk*sOut}); + } else { + task.push({cmd: "GET", out:0, var: 0, len: sMid*pointsInChunk}); + } + promises.push(tm.queueAction(task).then( (r) => { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix end: ${i}/${nChunks}`); + return r; + })); + } + + chunks = await Promise.all(promises); + for (let i = 0; i< nChunks; i++) chunks[i] = chunks[i][0]; + + for (let i = l2Chunk+1; i<=bits; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join: ${i}/${bits}`); + const nGroups = 1 << (bits - i); + const nChunksPerGroup = nChunks / nGroups; + const opPromises = []; + for (let j=0; j { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join ${i}/${bits} ${j+1}/${nGroups} ${k}/${nChunksPerGroup/2}`); + return r; + })); + } + } + + const res = await Promise.all(opPromises); + for (let j=0; j0; i--) { + buffOut.set(chunks[i], p); + p += pointsInChunk*sOut; + delete chunks[i]; // Liberate mem + } + buffOut.set(chunks[0].slice(0, (pointsInChunk-1)*sOut), p); + delete chunks[0]; + } else { + for (let i=0; i (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + async function _fftExtInv(buff, inType, outType, logger, loggerTxt) { + let b1, b2; + b1 = buff.slice( 0 , buff.byteLength/2); + b2 = buff.slice( buff.byteLength/2, buff.byteLength); + + const promises = []; + + promises.push( _fft(b1, true, inType, "jacobian", logger, loggerTxt)); + promises.push( _fft(b2, true, inType, "jacobian", logger, loggerTxt)); + + [b1, b2] = await Promise.all(promises); + + const res1 = await _fftJoinExt(b1, b2, "fftJoinExtInv", Fr.one, Fr.shiftInv, "jacobian", outType, logger, loggerTxt); + + let buffOut; + if (res1[0].byteLength > (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + + async function _fftJoinExt(buff1, buff2, fn, first, inc, inType, outType, logger, loggerTxt) { + const MAX_CHUNK_SIZE = 1<<16; + const MIN_CHUNK_SIZE = 1<<4; + + let fnName; + let fnIn2Mid, fnMid2Out; + let sOut, sIn, sMid; + + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + fnName = "g1m_"+fn; + if (outType == "affine") { + fnMid2Out = "g1m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + fnName = "g2m_"+fn; + sMid = G.F.n8*3; + if (outType == "affine") { + fnMid2Out = "g2m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = Fr.n8; + sOut = Fr.n8; + sMid = Fr.n8; + fnName = "frm_" + fn; + } else { + throw new Error("Invalid group"); + } + + if (buff1.byteLength != buff2.byteLength) { + throw new Error("Invalid buffer size"); + } + const nPoints = Math.floor(buff1.byteLength / sIn); + if (nPoints != 1 << utils_log2(nPoints)) { + throw new Error("Invalid number of points"); + } + + let chunkSize = Math.floor(nPoints /tm.concurrency); + if (chunkSize < MIN_CHUNK_SIZE) chunkSize = MIN_CHUNK_SIZE; + if (chunkSize > MAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + + const opPromises = []; + + for (let i=0; i { + if (logger) logger.debug(`${loggerTxt}: fftJoinExt End: ${i}/${nPoints}`); + return r; + }) + ); + } + + const result = await Promise.all(opPromises); + + let fullBuffOut1; + let fullBuffOut2; + if (nPoints * sOut > 1<<28) { + fullBuffOut1 = new BigBuffer(nPoints*sOut); + fullBuffOut2 = new BigBuffer(nPoints*sOut); + } else { + fullBuffOut1 = new Uint8Array(nPoints*sOut); + fullBuffOut2 = new Uint8Array(nPoints*sOut); + } + + let p =0; + for (let i=0; i Fr.s+1) { + if (logger) logger.error("lagrangeEvaluations input too big"); + throw new Error("lagrangeEvaluations input too big"); + } + + let t0 = buff.slice(0, buff.byteLength/2); + let t1 = buff.slice(buff.byteLength/2, buff.byteLength); + + + const shiftToSmallM = Fr.exp(Fr.shift, nPoints/2); + const sConst = Fr.inv( Fr.sub(Fr.one, shiftToSmallM)); + + [t0, t1] = await _fftJoinExt(t0, t1, "prepareLagrangeEvaluation", sConst, Fr.shiftInv, inType, "jacobian", logger, loggerTxt + " prep"); + + const promises = []; + + promises.push( _fft(t0, true, "jacobian", outType, logger, loggerTxt + " t0")); + promises.push( _fft(t1, true, "jacobian", outType, logger, loggerTxt + " t1")); + + [t0, t1] = await Promise.all(promises); + + let buffOut; + if (t0.byteLength > (1<<28)) { + buffOut = new BigBuffer(t0.byteLength*2); + } else { + buffOut = new Uint8Array(t0.byteLength*2); + } + + buffOut.set(t0); + buffOut.set(t1, t0.byteLength); + + return buffOut; + }; + + G.fftMix = async function fftMix(buff) { + const sG = G.F.n8*3; + let fnName, fnFFTJoin; + if (groupName == "G1") { + fnName = "g1m_fftMix"; + fnFFTJoin = "g1m_fftJoin"; + } else if (groupName == "G2") { + fnName = "g2m_fftMix"; + fnFFTJoin = "g2m_fftJoin"; + } else if (groupName == "Fr") { + fnName = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } else { + throw new Error("Invalid group"); + } + + const nPoints = Math.floor(buff.byteLength / sG); + const power = utils_log2(nPoints); + + let nChunks = 1 << utils_log2(tm.concurrency); + + if (nPoints <= nChunks*2) nChunks = 1; + + const pointsPerChunk = nPoints / nChunks; + + const powerChunk = utils_log2(pointsPerChunk); + + const opPromises = []; + for (let i=0; i=0; i--) { + fullBuffOut.set(result[i][0], p); + p+=result[i][0].byteLength; + } + + return fullBuffOut; + }; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine.js + + + + + + + + + + + +async function buildEngine(params) { + + const tm = await buildThreadManager(params.wasm, params.singleThread); + + + const curve = {}; + + curve.q = scalar_e(params.wasm.q); + curve.r = scalar_e(params.wasm.r); + curve.name = params.name; + curve.tm = tm; + curve.prePSize = params.wasm.prePSize; + curve.preQSize = params.wasm.preQSize; + curve.Fr = new WasmField1(tm, "frm", params.n8r, params.r); + curve.F1 = new WasmField1(tm, "f1m", params.n8q, params.q); + curve.F2 = new WasmField2(tm, "f2m", curve.F1); + curve.G1 = new WasmCurve(tm, "g1m", curve.F1, params.wasm.pG1gen, params.wasm.pG1b, params.cofactorG1); + curve.G2 = new WasmCurve(tm, "g2m", curve.F2, params.wasm.pG2gen, params.wasm.pG2b, params.cofactorG2); + curve.F6 = new WasmField3(tm, "f6m", curve.F2); + curve.F12 = new WasmField2(tm, "ftm", curve.F6); + + curve.Gt = curve.F12; + + buildBatchApplyKey(curve, "G1"); + buildBatchApplyKey(curve, "G2"); + buildBatchApplyKey(curve, "Fr"); + + buildMultiexp(curve, "G1"); + buildMultiexp(curve, "G2"); + + buildFFT(curve, "G1"); + buildFFT(curve, "G2"); + buildFFT(curve, "Fr"); + + buildPairing(curve); + + curve.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i= 0) { + curve = await bn128_buildBn128(singleThread, plugins); + } else if (["BLS12381"].indexOf(normName) >= 0) { + curve = await bls12381_buildBls12381(singleThread, plugins); + } else { + throw new Error(`Curve not supported: ${name}`); + } + return curve; + + function normalizeName(n) { + return n.toUpperCase().match(/[A-Za-z0-9]+/g).join(""); + } + +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/main.js + + +const main_Scalar=scalar_namespaceObject; + + + + + + + + + + + + + + +const main_utils = utils_namespaceObject; + + + + + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/babyjub.js + + +async function babyjub_buildBabyJub() { + const bn128 = await curves_getCurveFromName("bn128", true); + return new BabyJub(bn128.Fr); +} + +class BabyJub { + constructor(F) { + this.F = F; + this.p = main_Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + this.pm1d2 = main_Scalar.div(main_Scalar.sub(this.p, main_Scalar.e(1)), main_Scalar.e(2)); + + this.Generator = [ + F.e("995203441582195749578291179787384436505546430278305826713579947235728471134"), + F.e("5472060717959818805561601436314318772137091100104008585924551046643952123905") + ]; + this.Base8 = [ + F.e("5299619240641551281634865583518297030282874472190772894086521144482721001553"), + F.e("16950150798460657717958625567821834550301663161624707787222815936182638968203") + ]; + this.order = main_Scalar.fromString("21888242871839275222246405745257275088614511777268538073601725287587578984328"); + this.subOrder = main_Scalar.shiftRight(this.order, 3); + this.A = F.e("168700"); + this.D = F.e("168696"); + } + + + addPoint(a,b) { + const F = this.F; + + const res = []; + + /* does the equivalent of: + res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) * bigInt(bigInt("1") + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q); + res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt("1") - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q); + */ + + const beta = F.mul(a[0],b[1]); + const gamma = F.mul(a[1],b[0]); + const delta = F.mul( + F.sub(a[1], F.mul(this.A, a[0])), + F.add(b[0], b[1]) + ); + const tau = F.mul(beta, gamma); + const dtau = F.mul(this.D, tau); + + res[0] = F.div( + F.add(beta, gamma), + F.add(F.one, dtau) + ); + + res[1] = F.div( + F.add(delta, F.sub(F.mul(this.A,beta), gamma)), + F.sub(F.one, dtau) + ); + + return res; + } + + mulPointEscalar(base, e) { + const F = this.F; + let res = [F.e("0"),F.e("1")]; + let rem = e; + let exp = base; + + while (! main_Scalar.isZero(rem)) { + if (main_Scalar.isOdd(rem)) { + res = this.addPoint(res, exp); + } + exp = this.addPoint(exp, exp); + rem = main_Scalar.shiftRight(rem, 1); + } + + return res; + } + + inSubgroup(P) { + const F = this.F; + if (!this.inCurve(P)) return false; + const res= this.mulPointEscalar(P, this.subOrder); + return (F.isZero(res[0]) && F.eq(res[1], F.one)); + } + + inCurve(P) { + const F = this.F; + const x2 = F.square(P[0]); + const y2 = F.square(P[1]); + + if (!F.eq( + F.add(F.mul(this.A, x2), y2), + F.add(F.one, F.mul(F.mul(x2, y2), this.D)))) return false; + + return true; + } + + packPoint(P) { + const F = this.F; + const buff = new Uint8Array(32); + F.toRprLE(buff, 0, P[1]); + const n = F.toObject(P[0]); + if (main_Scalar.gt(n, this.pm1d2)) { + buff[31] = buff[31] | 0x80; + } + return buff; + } + + unpackPoint(buff) { + const F = this.F; + let sign = false; + const P = new Array(2); + if (buff[31] & 0x80) { + sign = true; + buff[31] = buff[31] & 0x7F; + } + P[1] = F.fromRprLE(buff, 0); + if (main_Scalar.gt(F.toObject(P[1]), this.p)) return null; + + const y2 = F.square(P[1]); + + const x2 = F.div( + F.sub(F.one, y2), + F.sub(this.A, F.mul(this.D, y2)) + ); + + const x2h = F.exp(x2, F.half); + if (! F.eq(F.one, x2h)) return null; + + let x = F.sqrt(x2); + + if (x == null) return null; + + if (sign) x = F.neg(x); + + P[0] = x; + + return P; + } +} + +// EXTERNAL MODULE: ./node_modules/blake2b/index.js +var blake2b = __webpack_require__(72206); +// EXTERNAL MODULE: ./node_modules/blake-hash/js.js +var js = __webpack_require__(60654); +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/pedersen_hash.js +/* provided dependency */ var pedersen_hash_Buffer = __webpack_require__(48287)["Buffer"]; + + + + + +const GENPOINT_PREFIX = "PedersenGenerator"; +const windowSize = 4; +const nWindowsPerSegment = 50; + +async function pedersen_hash_buildPedersenHash() { + const babyJub = await babyjub_buildBabyJub(); + return new PedersenHash(babyJub); +} + +class PedersenHash { + + constructor(babyJub) { + this.babyJub = babyJub; + this.bases = []; + } + + baseHash(type, S) { + if (type == "blake") { + return js("blake256").update(S).digest(); + } else if (type == "blake2b") { + return pedersen_hash_Buffer.from(blake2b(32).update(pedersen_hash_Buffer.from(S)).digest()); + } + } + + hash(msg, options) { + options = options || {}; + options.baseHash = options.baseHash || "blake"; + const babyJub = this.babyJub; + const bitsPerSegment = windowSize*nWindowsPerSegment; + const bits = this.buffer2bits(msg); + + const nSegments = Math.floor((bits.length - 1)/(windowSize*nWindowsPerSegment)) +1; + + let accP = [babyJub.F.zero,babyJub.F.one]; + + for (let s=0; s> 1; + res[i*8+2] = (b & 0x04) >> 2; + res[i*8+3] = (b & 0x08) >> 3; + res[i*8+4] = (b & 0x10) >> 4; + res[i*8+5] = (b & 0x20) >> 5; + res[i*8+6] = (b & 0x40) >> 6; + res[i*8+7] = (b & 0x80) >> 7; + } + return res; + } +} + + + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimc7.js + + + + +const SEED = "mimc"; +const NROUNDS = 91; + +async function mimc7_buildMimc7() { + const bn128 = await getCurveFromName("bn128", true); + return new Mimc7(bn128.Fr); +} + + +class Mimc7 { + constructor (F) { + this.F = F; + this.cts = this.getConstants(SEED, 91); + } + + getIV(seed) { + const F = this.F; + if (typeof seed === "undefined") seed = SEED; + const c = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(seed+"_iv")); + const cn = Scalar.e(c); + const iv = Scalar.mod(cn, F.p); + return iv; + }; + + getConstants(seed, nRounds) { + const F = this.F; + if (typeof seed === "undefined") seed = SEED; + if (typeof nRounds === "undefined") nRounds = NROUNDS; + const cts = new Array(nRounds); + let c = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(SEED)); + for (let i=1; i { + let buff; + let n; + if (Array.isArray(arr)) { + n = arr.length; + buff = new Uint8Array(n*32); + for (let i=0; i16)) throw new Error("Invalid poseidon size"); + + if (typeof state == "undefined") { + state = F.zero; + } else { + state = F.e(state); + } + bn128.tm.setBuff(pState, state); + nOut = nOut || 1; + + bn128.tm.instance.exports.poseidon(pState, pIn, n, pOut, nOut); + if (nOut == 1) { + return bn128.tm.getBuff(pOut, 32); + } else { + const out = []; + for (let i=0; i { + try { + if ("test".normalize(form) !== "test") { + throw new Error("bad normalize"); + } + ; + } + catch (error) { + missing.push(form); + } + }); + if (missing.length) { + throw new Error("missing " + missing.join(", ")); + } + if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) { + throw new Error("broken implementation"); + } + } + catch (error) { + return error.message; + } + return null; +} +const _normalizeError = _checkNormalize(); +var LogLevel; +(function (LogLevel) { + LogLevel["DEBUG"] = "DEBUG"; + LogLevel["INFO"] = "INFO"; + LogLevel["WARNING"] = "WARNING"; + LogLevel["ERROR"] = "ERROR"; + LogLevel["OFF"] = "OFF"; +})(LogLevel || (LogLevel = {})); +var ErrorCode; +(function (ErrorCode) { + /////////////////// + // Generic Errors + // Unknown Error + ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; + // Not Implemented + ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; + // Unsupported Operation + // - operation + ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; + // Network Error (i.e. Ethereum Network, such as an invalid chain ID) + // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown) + ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR"; + // Some sort of bad response from the server + ErrorCode["SERVER_ERROR"] = "SERVER_ERROR"; + // Timeout + ErrorCode["TIMEOUT"] = "TIMEOUT"; + /////////////////// + // Operational Errors + // Buffer Overrun + ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; + // Numeric Fault + // - operation: the operation being executed + // - fault: the reason this faulted + ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT"; + /////////////////// + // Argument Errors + // Missing new operator to an object + // - name: The name of the class + ErrorCode["MISSING_NEW"] = "MISSING_NEW"; + // Invalid argument (e.g. value is incompatible with type) to a function: + // - argument: The argument name that was invalid + // - value: The value of the argument + ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; + // Missing argument to a function: + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; + // Too many arguments + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; + /////////////////// + // Blockchain Errors + // Call exception + // - transaction: the transaction + // - address?: the contract address + // - args?: The arguments passed into the function + // - method?: The Solidity method signature + // - errorSignature?: The EIP848 error signature + // - errorArgs?: The EIP848 error parameters + // - reason: The reason (only for EIP848 "Error(string)") + ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION"; + // Insufficient funds (< value + gasLimit * gasPrice) + // - transaction: the transaction attempted + ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; + // Nonce has already been used + // - transaction: the transaction attempted + ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED"; + // The replacement fee for the transaction is too low + // - transaction: the transaction attempted + ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; + // The gas limit could not be estimated + // - transaction: the transaction passed to estimateGas + ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; + // The transaction was replaced by one with a higher gas price + // - reason: "cancelled", "replaced" or "repriced" + // - cancelled: true if reason == "cancelled" or reason == "replaced") + // - hash: original transaction hash + // - replacement: the full TransactionsResponse for the replacement + // - receipt: the receipt of the replacement + ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; + /////////////////// + // Interaction Errors + // The user rejected the action, such as signing a message or sending + // a transaction + ErrorCode["ACTION_REJECTED"] = "ACTION_REJECTED"; +})(ErrorCode || (ErrorCode = {})); +; +const HEX = "0123456789abcdef"; +class Logger { + constructor(version) { + Object.defineProperty(this, "version", { + enumerable: true, + value: version, + writable: false + }); + } + _log(logLevel, args) { + const level = logLevel.toLowerCase(); + if (LogLevels[level] == null) { + this.throwArgumentError("invalid log level name", "logLevel", logLevel); + } + if (_logLevel > LogLevels[level]) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this._log(Logger.levels.DEBUG, args); + } + info(...args) { + this._log(Logger.levels.INFO, args); + } + warn(...args) { + this._log(Logger.levels.WARNING, args); + } + makeError(message, code, params) { + // Errors are being censored + if (_censorErrors) { + return this.makeError("censored error", code, {}); + } + if (!code) { + code = Logger.errors.UNKNOWN_ERROR; + } + if (!params) { + params = {}; + } + const messageDetails = []; + Object.keys(params).forEach((key) => { + const value = params[key]; + try { + if (value instanceof Uint8Array) { + let hex = ""; + for (let i = 0; i < value.length; i++) { + hex += HEX[value[i] >> 4]; + hex += HEX[value[i] & 0x0f]; + } + messageDetails.push(key + "=Uint8Array(0x" + hex + ")"); + } + else { + messageDetails.push(key + "=" + JSON.stringify(value)); + } + } + catch (error) { + messageDetails.push(key + "=" + JSON.stringify(params[key].toString())); + } + }); + messageDetails.push(`code=${code}`); + messageDetails.push(`version=${this.version}`); + const reason = message; + let url = ""; + switch (code) { + case ErrorCode.NUMERIC_FAULT: { + url = "NUMERIC_FAULT"; + const fault = message; + switch (fault) { + case "overflow": + case "underflow": + case "division-by-zero": + url += "-" + fault; + break; + case "negative-power": + case "negative-width": + url += "-unsupported"; + break; + case "unbound-bitwise-result": + url += "-unbound-result"; + break; + } + break; + } + case ErrorCode.CALL_EXCEPTION: + case ErrorCode.INSUFFICIENT_FUNDS: + case ErrorCode.MISSING_NEW: + case ErrorCode.NONCE_EXPIRED: + case ErrorCode.REPLACEMENT_UNDERPRICED: + case ErrorCode.TRANSACTION_REPLACED: + case ErrorCode.UNPREDICTABLE_GAS_LIMIT: + url = code; + break; + } + if (url) { + message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]"; + } + if (messageDetails.length) { + message += " (" + messageDetails.join(", ") + ")"; + } + // @TODO: Any?? + const error = new Error(message); + error.reason = reason; + error.code = code; + Object.keys(params).forEach(function (key) { + error[key] = params[key]; + }); + return error; + } + throwError(message, code, params) { + throw this.makeError(message, code, params); + } + throwArgumentError(message, name, value) { + return this.throwError(message, Logger.errors.INVALID_ARGUMENT, { + argument: name, + value: value + }); + } + assert(condition, message, code, params) { + if (!!condition) { + return; + } + this.throwError(message, code, params); + } + assertArgument(condition, message, name, value) { + if (!!condition) { + return; + } + this.throwArgumentError(message, name, value); + } + checkNormalize(message) { + if (message == null) { + message = "platform missing String.prototype.normalize"; + } + if (_normalizeError) { + this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "String.prototype.normalize", form: _normalizeError + }); + } + } + checkSafeUint53(value, message) { + if (typeof (value) !== "number") { + return; + } + if (message == null) { + message = "value not safe"; + } + if (value < 0 || value >= 0x1fffffffffffff) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "out-of-safe-range", + value: value + }); + } + if (value % 1) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "non-integer", + value: value + }); + } + } + checkArgumentCount(count, expectedCount, message) { + if (message) { + message = ": " + message; + } + else { + message = ""; + } + if (count < expectedCount) { + this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + } + checkNew(target, kind) { + if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + checkAbstract(target, kind) { + if (target === kind) { + this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" }); + } + else if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + static globalLogger() { + if (!_globalLogger) { + _globalLogger = new Logger(version); + } + return _globalLogger; + } + static setCensorship(censorship, permanent) { + if (!censorship && permanent) { + this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + if (_permanentCensorErrors) { + if (!censorship) { + return; + } + this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + _censorErrors = !!censorship; + _permanentCensorErrors = !!permanent; + } + static setLogLevel(logLevel) { + const level = LogLevels[logLevel.toLowerCase()]; + if (level == null) { + Logger.globalLogger().warn("invalid log level - " + logLevel); + return; + } + _logLevel = level; + } + static from(version) { + return new Logger(version); + } +} +Logger.errors = ErrorCode; +Logger.levels = LogLevel; +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/_version.js +const _version_version = "bytes/5.7.0"; +//# sourceMappingURL=_version.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/index.js + + + +const logger = new Logger(_version_version); +/////////////////////////////// +function isHexable(value) { + return !!(value.toHexString); +} +function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function () { + const args = Array.prototype.slice.call(arguments); + return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); + }; + return array; +} +function isBytesLike(value) { + return ((isHexString(value) && !(value.length % 2)) || isBytes(value)); +} +function isInteger(value) { + return (typeof (value) === "number" && value == value && (value % 1) === 0); +} +function isBytes(value) { + if (value == null) { + return false; + } + if (value.constructor === Uint8Array) { + return true; + } + if (typeof (value) === "string") { + return false; + } + if (!isInteger(value.length) || value.length < 0) { + return false; + } + for (let i = 0; i < value.length; i++) { + const v = value[i]; + if (!isInteger(v) || v < 0 || v >= 256) { + return false; + } + } + return true; +} +function lib_esm_arrayify(value, options) { + if (!options) { + options = {}; + } + if (typeof (value) === "number") { + logger.checkSafeUint53(value, "invalid arrayify value"); + const result = []; + while (value) { + result.unshift(value & 0xff); + value = parseInt(String(value / 256)); + } + if (result.length === 0) { + result.push(0); + } + return addSlice(new Uint8Array(result)); + } + if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + value = value.toHexString(); + } + if (isHexString(value)) { + let hex = value.substring(2); + if (hex.length % 2) { + if (options.hexPad === "left") { + hex = "0" + hex; + } + else if (options.hexPad === "right") { + hex += "0"; + } + else { + logger.throwArgumentError("hex data is odd-length", "value", value); + } + } + const result = []; + for (let i = 0; i < hex.length; i += 2) { + result.push(parseInt(hex.substring(i, i + 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + if (isBytes(value)) { + return addSlice(new Uint8Array(value)); + } + return logger.throwArgumentError("invalid arrayify value", "value", value); +} +function concat(items) { + const objects = items.map(item => lib_esm_arrayify(item)); + const length = objects.reduce((accum, item) => (accum + item.length), 0); + const result = new Uint8Array(length); + objects.reduce((offset, object) => { + result.set(object, offset); + return offset + object.length; + }, 0); + return addSlice(result); +} +function stripZeros(value) { + let result = lib_esm_arrayify(value); + if (result.length === 0) { + return result; + } + // Find the first non-zero entry + let start = 0; + while (start < result.length && result[start] === 0) { + start++; + } + // If we started with zeros, strip them + if (start) { + result = result.slice(start); + } + return result; +} +function zeroPad(value, length) { + value = lib_esm_arrayify(value); + if (value.length > length) { + logger.throwArgumentError("value out of range", "value", arguments[0]); + } + const result = new Uint8Array(length); + result.set(value, length - value.length); + return addSlice(result); +} +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (length && value.length !== 2 + 2 * length) { + return false; + } + return true; +} +const HexCharacters = "0123456789abcdef"; +function hexlify(value, options) { + if (!options) { + options = {}; + } + if (typeof (value) === "number") { + logger.checkSafeUint53(value, "invalid hexlify value"); + let hex = ""; + while (value) { + hex = HexCharacters[value & 0xf] + hex; + value = Math.floor(value / 16); + } + if (hex.length) { + if (hex.length % 2) { + hex = "0" + hex; + } + return "0x" + hex; + } + return "0x00"; + } + if (typeof (value) === "bigint") { + value = value.toString(16); + if (value.length % 2) { + return ("0x0" + value); + } + return "0x" + value; + } + if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + return value.toHexString(); + } + if (isHexString(value)) { + if (value.length % 2) { + if (options.hexPad === "left") { + value = "0x0" + value.substring(2); + } + else if (options.hexPad === "right") { + value += "0"; + } + else { + logger.throwArgumentError("hex data is odd-length", "value", value); + } + } + return value.toLowerCase(); + } + if (isBytes(value)) { + let result = "0x"; + for (let i = 0; i < value.length; i++) { + let v = value[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; + } + return logger.throwArgumentError("invalid hexlify value", "value", value); +} +/* +function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number { + if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") { + return "0x0" + value.substring(2); + } + return value; +} +*/ +function hexDataLength(data) { + if (typeof (data) !== "string") { + data = hexlify(data); + } + else if (!isHexString(data) || (data.length % 2)) { + return null; + } + return (data.length - 2) / 2; +} +function hexDataSlice(data, offset, endOffset) { + if (typeof (data) !== "string") { + data = hexlify(data); + } + else if (!isHexString(data) || (data.length % 2)) { + logger.throwArgumentError("invalid hexData", "value", data); + } + offset = 2 + 2 * offset; + if (endOffset != null) { + return "0x" + data.substring(offset, 2 + 2 * endOffset); + } + return "0x" + data.substring(offset); +} +function hexConcat(items) { + let result = "0x"; + items.forEach((item) => { + result += hexlify(item).substring(2); + }); + return result; +} +function hexValue(value) { + const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" })); + if (trimmed === "0x") { + return "0x0"; + } + return trimmed; +} +function hexStripZeros(value) { + if (typeof (value) !== "string") { + value = hexlify(value); + } + if (!isHexString(value)) { + logger.throwArgumentError("invalid hex string", "value", value); + } + value = value.substring(2); + let offset = 0; + while (offset < value.length && value[offset] === "0") { + offset++; + } + return "0x" + value.substring(offset); +} +function hexZeroPad(value, length) { + if (typeof (value) !== "string") { + value = hexlify(value); + } + else if (!isHexString(value)) { + logger.throwArgumentError("invalid hex string", "value", value); + } + if (value.length > 2 * length + 2) { + logger.throwArgumentError("value out of range", "value", arguments[1]); + } + while (value.length < 2 * length + 2) { + value = "0x0" + value.substring(2); + } + return value; +} +function splitSignature(signature) { + const result = { + r: "0x", + s: "0x", + _vs: "0x", + recoveryParam: 0, + v: 0, + yParityAndS: "0x", + compact: "0x" + }; + if (isBytesLike(signature)) { + let bytes = lib_esm_arrayify(signature); + // Get the r, s and v + if (bytes.length === 64) { + // EIP-2098; pull the v from the top bit of s and clear it + result.v = 27 + (bytes[32] >> 7); + bytes[32] &= 0x7f; + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + } + else if (bytes.length === 65) { + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + result.v = bytes[64]; + } + else { + logger.throwArgumentError("invalid signature string", "signature", signature); + } + // Allow a recid to be used as the v + if (result.v < 27) { + if (result.v === 0 || result.v === 1) { + result.v += 27; + } + else { + logger.throwArgumentError("signature invalid v byte", "signature", signature); + } + } + // Compute recoveryParam from v + result.recoveryParam = 1 - (result.v % 2); + // Compute _vs from recoveryParam and s + if (result.recoveryParam) { + bytes[32] |= 0x80; + } + result._vs = hexlify(bytes.slice(32, 64)); + } + else { + result.r = signature.r; + result.s = signature.s; + result.v = signature.v; + result.recoveryParam = signature.recoveryParam; + result._vs = signature._vs; + // If the _vs is available, use it to populate missing s, v and recoveryParam + // and verify non-missing s, v and recoveryParam + if (result._vs != null) { + const vs = zeroPad(lib_esm_arrayify(result._vs), 32); + result._vs = hexlify(vs); + // Set or check the recid + const recoveryParam = ((vs[0] >= 128) ? 1 : 0); + if (result.recoveryParam == null) { + result.recoveryParam = recoveryParam; + } + else if (result.recoveryParam !== recoveryParam) { + logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature); + } + // Set or check the s + vs[0] &= 0x7f; + const s = hexlify(vs); + if (result.s == null) { + result.s = s; + } + else if (result.s !== s) { + logger.throwArgumentError("signature v mismatch _vs", "signature", signature); + } + } + // Use recid and v to populate each other + if (result.recoveryParam == null) { + if (result.v == null) { + logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature); + } + else if (result.v === 0 || result.v === 1) { + result.recoveryParam = result.v; + } + else { + result.recoveryParam = 1 - (result.v % 2); + } + } + else { + if (result.v == null) { + result.v = 27 + result.recoveryParam; + } + else { + const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2)); + if (result.recoveryParam !== recId) { + logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature); + } + } + } + if (result.r == null || !isHexString(result.r)) { + logger.throwArgumentError("signature missing or invalid r", "signature", signature); + } + else { + result.r = hexZeroPad(result.r, 32); + } + if (result.s == null || !isHexString(result.s)) { + logger.throwArgumentError("signature missing or invalid s", "signature", signature); + } + else { + result.s = hexZeroPad(result.s, 32); + } + const vs = lib_esm_arrayify(result.s); + if (vs[0] >= 128) { + logger.throwArgumentError("signature s out of range", "signature", signature); + } + if (result.recoveryParam) { + vs[0] |= 0x80; + } + const _vs = hexlify(vs); + if (result._vs) { + if (!isHexString(result._vs)) { + logger.throwArgumentError("signature invalid _vs", "signature", signature); + } + result._vs = hexZeroPad(result._vs, 32); + } + // Set or check the _vs + if (result._vs == null) { + result._vs = _vs; + } + else if (result._vs !== _vs) { + logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature); + } + } + result.yParityAndS = result._vs; + result.compact = result.r + result.yParityAndS.substring(2); + return result; +} +function joinSignature(signature) { + signature = splitSignature(signature); + return hexlify(concat([ + signature.r, + signature.s, + (signature.recoveryParam ? "0x1c" : "0x1b") + ])); +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/keccak256/lib.esm/index.js + + + +function keccak256(data) { + return '0x' + sha3_default().keccak_256(lib_esm_arrayify(data)); +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/_version.js +const lib_esm_version_version = "strings/5.7.0"; +//# sourceMappingURL=_version.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/utf8.js + + + + +const utf8_logger = new Logger(lib_esm_version_version); +/////////////////////////////// +var UnicodeNormalizationForm; +(function (UnicodeNormalizationForm) { + UnicodeNormalizationForm["current"] = ""; + UnicodeNormalizationForm["NFC"] = "NFC"; + UnicodeNormalizationForm["NFD"] = "NFD"; + UnicodeNormalizationForm["NFKC"] = "NFKC"; + UnicodeNormalizationForm["NFKD"] = "NFKD"; +})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); +; +var Utf8ErrorReason; +(function (Utf8ErrorReason) { + // A continuation byte was present where there was nothing to continue + // - offset = the index the codepoint began in + Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; + // An invalid (non-continuation) byte to start a UTF-8 codepoint was found + // - offset = the index the codepoint began in + Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix"; + // The string is too short to process the expected codepoint + // - offset = the index the codepoint began in + Utf8ErrorReason["OVERRUN"] = "string overrun"; + // A missing continuation byte was expected but not found + // - offset = the index the continuation byte was expected at + Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte"; + // The computed code point is outside the range for UTF-8 + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; outside the UTF-8 range + Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range"; + // UTF-8 strings may not contain UTF-16 surrogate pairs + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range + Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate"; + // The string is an overlong representation + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; already bounds checked + Utf8ErrorReason["OVERLONG"] = "overlong representation"; +})(Utf8ErrorReason || (Utf8ErrorReason = {})); +; +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return utf8_logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === Utf8ErrorReason.OVERRUN) { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === Utf8ErrorReason.OVERLONG) { + output.push(badCodepoint); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +// Common error handing strategies +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + bytes = arrayify(bytes); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result); + } + else { + i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { + if (form != UnicodeNormalizationForm.current) { + utf8_logger.checkNormalize(); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return lib_esm_arrayify(result); +} +; +function escapeChar(value) { + const hex = ("0000" + value.toString(16)); + return "\\u" + hex.substring(hex.length - 4); +} +function _toEscapedUtf8String(bytes, onError) { + return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => { + if (codePoint < 256) { + switch (codePoint) { + case 8: return "\\b"; + case 9: return "\\t"; + case 10: return "\\n"; + case 13: return "\\r"; + case 34: return "\\\""; + case 92: return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 0xffff) { + return escapeChar(codePoint); + } + codePoint -= 0x10000; + return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); + }).join("") + '"'; +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +//# sourceMappingURL=utf8.js.map +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimcsponge.js + + + +const mimcsponge_SEED = "mimcsponge"; +const mimcsponge_NROUNDS = 220; + +async function mimcsponge_buildMimcSponge() { + const bn128 = await curves_getCurveFromName("bn128", true); + return new MimcSponge(bn128.Fr); +} + +class MimcSponge { + constructor (F) { + this.F = F; + this.cts = this.getConstants(mimcsponge_SEED, mimcsponge_NROUNDS); + } + + getIV (seed) { + const F = this.F; + if (typeof seed === "undefined") seed = mimcsponge_SEED; + const c = keccak256(toUtf8Bytes(seed+"_iv")); + const cn = main_Scalar.e(c); + const iv = cn.mod(F.p); + return iv; + }; + + getConstants (seed, nRounds) { + const F = this.F; + if (typeof seed === "undefined") seed = mimcsponge_SEED; + if (typeof nRounds === "undefined") nRounds = mimcsponge_NROUNDS; + const cts = new Array(nRounds); + let c = keccak256(toUtf8Bytes(mimcsponge_SEED));; + for (let i=1; i= this.babyJub.subOrder) return false; + + const hm = this.mimc7.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + verifyPoseidon(msg, sig, A) { + + // Check parameters + if (typeof sig != "object") return false; + if (!Array.isArray(sig.R8)) return false; + if (sig.R8.length!= 2) return false; + if (!this.babyJub.inCurve(sig.R8)) return false; + if (!Array.isArray(A)) return false; + if (A.length!= 2) return false; + if (!this.babyJub.inCurve(A)) return false; + if (sig.S>= this.babyJub.subOrder) return false; + + const hm = this.poseidon([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + verifyMiMCSponge(msg, sig, A) { + + // Check parameters + if (typeof sig != "object") return false; + if (!Array.isArray(sig.R8)) return false; + if (sig.R8.length!= 2) return false; + if (!this.babyJub.inCurve(sig.R8)) return false; + if (!Array.isArray(A)) return false; + if (A.length!= 2) return false; + if (!this.babyJub.inCurve(A)) return false; + if (sig.S>= this.babyJub.subOrder) return false; + + const hm = this.mimcSponge.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + packSignature(sig) { + const buff = new Uint8Array(64); + const R8p = this.babyJub.packPoint(sig.R8); + buff.set(R8p, 0) + const Sp = Scalar.toRprLE(buff, 32, sig.S, 32); + return buff; + } + + unpackSignature(sigBuff) { + return { + R8: this.babyJub.unpackPoint(sigBuff.slice(0,32)), + S: Scalar.fromRprLE(sigBuff, 32, 32) + }; + } +} + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/evmasm.js +// Copyright (c) 2018 Jordi Baylina +// License: LGPL-3.0+ +// + + + + +class evmasm_Contract { + constructor() { + this.code = []; + this.labels = {}; + this.pendingLabels = {}; + } + + createTxData() { + let C; + + // Check all labels are defined + const pendingLabels = Object.keys(this.pendingLabels); + if (pendingLabels.length>0) { + throw new Error("Lables not defined: "+ pendingLabels.join(", ")); + } + + let setLoaderLength = 0; + let genLoadedLength = -1; + + while (genLoadedLength!=setLoaderLength) { + setLoaderLength = genLoadedLength; + C = new evmasm_Contract(); + C.codesize(); + C.push(setLoaderLength); + C.push(0); + C.codecopy(); + + C.push(this.code.length); + C.push(0); + C.return(); + genLoadedLength = C.code.length; + } + + return ethers.utils.hexlify(C.code.concat(this.code)); + } + + stop() { this.code.push(0x00); } + add() { this.code.push(0x01); } + mul() { this.code.push(0x02); } + sub() { this.code.push(0x03); } + div() { this.code.push(0x04); } + sdiv() { this.code.push(0x05); } + mod() { this.code.push(0x06); } + smod() { this.code.push(0x07); } + addmod() { this.code.push(0x08); } + mulmod() { this.code.push(0x09); } + exp() { this.code.push(0x0a); } + signextend() { this.code.push(0x0b); } + + lt() { this.code.push(0x10); } + gt() { this.code.push(0x11); } + slt() { this.code.push(0x12); } + sgt() { this.code.push(0x13); } + eq() { this.code.push(0x14); } + iszero() { this.code.push(0x15); } + and() { this.code.push(0x16); } + or() { this.code.push(0x17); } + shor() { this.code.push(0x18); } + not() { this.code.push(0x19); } + byte() { this.code.push(0x1a); } + + keccak() { this.code.push(0x20); } + sha3() { this.code.push(0x20); } // alias + + address() { this.code.push(0x30); } + balance() { this.code.push(0x31); } + origin() { this.code.push(0x32); } + caller() { this.code.push(0x33); } + callvalue() { this.code.push(0x34); } + calldataload() { this.code.push(0x35); } + calldatasize() { this.code.push(0x36); } + calldatacopy() { this.code.push(0x37); } + codesize() { this.code.push(0x38); } + codecopy() { this.code.push(0x39); } + gasprice() { this.code.push(0x3a); } + extcodesize() { this.code.push(0x3b); } + extcodecopy() { this.code.push(0x3c); } + returndatasize() { this.code.push(0x3d); } + returndatacopy() { this.code.push(0x3e); } + + blockhash() { this.code.push(0x40); } + coinbase() { this.code.push(0x41); } + timestamp() { this.code.push(0x42); } + number() { this.code.push(0x43); } + difficulty() { this.code.push(0x44); } + gaslimit() { this.code.push(0x45); } + + pop() { this.code.push(0x50); } + mload() { this.code.push(0x51); } + mstore() { this.code.push(0x52); } + mstore8() { this.code.push(0x53); } + sload() { this.code.push(0x54); } + sstore() { this.code.push(0x55); } + + _pushLabel(label) { + if (typeof this.labels[label] != "undefined") { + this.push(this.labels[label]); + } else { + this.pendingLabels[label] = this.pendingLabels[label] || []; + this.pendingLabels[label].push(this.code.length); + this.push("0x000000"); + } + } + + _fillLabel(label) { + if (!this.pendingLabels[label]) return; + + let dst = this.labels[label]; + + const dst3 = [dst >> 16, (dst >> 8) & 0xFF, dst & 0xFF]; + + this.pendingLabels[label].forEach((p) => { + for (let i=0; i<3; i++) { + this.code[p+i+1] = dst3[i]; + } + }); + + delete this.pendingLabels[label]; + } + + + jmp(label) { + if (typeof label !== "undefined") { + this._pushLabel(label); + } + this.code.push(0x56); + } + + jmpi(label) { + if (typeof label !== "undefined") { + this._pushLabel(label); + } + this.code.push(0x57); + } + + pc() { this.code.push(0x58); } + msize() { this.code.push(0x59); } + gas() { this.code.push(0x5a); } + label(name) { + if (typeof this.labels[name] != "undefined") { + throw new Error("Label already defined"); + } + this.labels[name] = this.code.length; + this.code.push(0x5b); + + this._fillLabel(name); + } + + push(data) { + if ((typeof data !== "string") || (data.slice(0,2) != "0x")) { + let v = Scalar.e(data); + if (Scalar.isNegative(v)) { + v = Scalar.add(Scalar.shl(Scalar.e(1), 256), v); + } + let S = Scalar.toString(v, 16); + if (S.length % 2) S = "0"+S; + S = "0x" +S; + data = S; + } + const d = ethers.utils.arrayify(data); + if (d.length == 0 || d.length > 32) { + throw new Error("Assertion failed"); + } + const a = []; + this.code.push(0x5F + d.length); + for (let i=0; i= 16) { + throw new Error("Assertion failed"); + } + this.code.push(0x80 + n); + } + + swap(n) { + if (n < 1 || n > 16) { + throw new Error("Assertion failed"); + } + this.code.push(0x8f + n); + } + + log0() { this.code.push(0xa0); } + log1() { this.code.push(0xa1); } + log2() { this.code.push(0xa2); } + log3() { this.code.push(0xa3); } + log4() { this.code.push(0xa4); } + + create() { this.code.push(0xf0); } + call() { this.code.push(0xf1); } + callcode() { this.code.push(0xf2); } + return() { this.code.push(0xf3); } + delegatecall() { this.code.push(0xf4); } + + staticcall() { this.code.push(0xfa); } + revert() { this.code.push(0xfd); } + invalid() { this.code.push(0xfe); } + selfdestruct() { this.code.push(0xff); } +} + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimc7_gencontract.js +// Copyright (c) 2018 Jordi Baylina +// License: LGPL-3.0+ +// + + + + + +function createCode(seed, n) { + + let ci = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(seed));; + + const C = new Contract(); + + C.push(0x44); + C.push("0x00"); + C.push("0x00"); + C.calldatacopy(); + C.push("0x0100000000000000000000000000000000000000000000000000000000"); + C.push("0x00"); + C.mload(); + C.div(); + C.push("0xd15ca109"); // MiMCpe7(uint256,uint256) +// C.push("0x8c42199e"); // MiMCpe7(uint256,uint256,uint256) + C.eq(); + C.jmpi("start"); + C.invalid(); + + C.label("start"); + C.push("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"); // q + C.push("0x24"); + C.mload(); // k q + + + C.dup(1); // q k q + C.dup(0); // q q k q + C.push("0x04"); + C.mload(); // x q q k q + C.dup(3); // k x q q k q + C.addmod(); // t=x+k q k q + C.dup(1); // q t q k q + C.dup(0); // q q t q k q + C.dup(2); // t q q t q k q + C.dup(0); // t t q q t q k q + C.mulmod(); // a=t^2 q t q k q + C.dup(1); // q a q t q k q + C.dup(1); // a q a q t q k q + C.dup(0); // a a q a q t q k q + C.mulmod(); // b=t^4 a q t q k q + C.mulmod(); // c=t^6 t q k q + C.mulmod(); // r=t^7 k q + + for (let i=0; i8)) throw new Error("Invalid number of inputs. Must be 1<=nInputs<=8"); + const t = nInputs + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + + const C = new Contract(); + + function saveM() { + for (let i=0; i=nRoundsP+nRoundsF/2)) { + for (let j=0; j { + res[k] = unsringifyConstants(Fr, o[k]); + }); + return res; + } else { + return o; + } +} + +async function poseidon_reference_buildPoseidon() { + const bn128 = await getCurveFromName("bn128", true); + + const F = bn128.Fr; + + // Parameters are generated by a reference script https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/generate_parameters_grain.sage + // Used like so: sage generate_parameters_grain.sage 1 0 254 2 8 56 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 + const {C, M} = unsringifyConstants(F, poseidonConstants); + + // Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8) + // Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py + // And rounded up to nearest integer that divides by t + const N_ROUNDS_F = 8; + const N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68]; + + const pow5 = a => F.mul(a, F.square(F.square(a, a))); + + function poseidon(inputs, initState, nOut) { + assert(inputs.length > 0); + assert(inputs.length <= N_ROUNDS_P.length); + + const t = inputs.length + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + + if (initState) { + initState = F.e(initState); + } else { + initState = F.zero; + } + nOut = nOut || 1; + + let state = [initState, ...inputs.map(a => F.e(a))]; + for (let r = 0; r < nRoundsF + nRoundsP; r++) { + state = state.map((a, i) => F.add(a, C[t - 2][r * t + i])); + + if (r < nRoundsF / 2 || r >= nRoundsF / 2 + nRoundsP) { + state = state.map(a => pow5(a)); + } else { + state[0] = pow5(state[0]); + } + + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[t - 2][i][j], a)), F.zero) + ); + } + if (nOut == 1) { + return state[0] + } else { + return state.slice(0, nOut); + } + } + + poseidon.F = F; + return poseidon; +} + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/poseidon_opt.js +// Parameters are generated by a reference script https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/generate_parameters_grain.sage +// Used like so: sage generate_parameters_grain.sage 1 0 254 2 8 56 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 + +// Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8) +// Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py +// And rounded up to nearest integer that divides by t + +// Optimization is taken from https://github.com/filecoin-project/neptune + + + + + + +function poseidon_opt_unsringifyConstants(Fr, o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return Fr.e(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return Fr.e(o); + } else if (Array.isArray(o)) { + return o.map(poseidon_opt_unsringifyConstants.bind(null, Fr)); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = poseidon_opt_unsringifyConstants(Fr, o[k]); + }); + return res; + } else { + return o; + } +} + +async function poseidon_opt_buildPoseidon() { + const bn128 = await getCurveFromName("bn128", true); + + const F = bn128.Fr; + + const opt = poseidon_opt_unsringifyConstants(F, poseidonConstants); + + const N_ROUNDS_F = 8; + const N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68]; + + const pow5 = a => F.mul(a, F.square(F.square(a, a))); + + function poseidon(inputs, initState, nOut) { + assert(inputs.length > 0); + assert(inputs.length <= N_ROUNDS_P.length); + + if (initState) { + initState = F.e(initState); + } else { + initState = F.zero; + } + nOut = nOut || 1; + + + const t = inputs.length + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + const C = opt.C[t-2]; + const S = opt.S[t-2]; + const M = opt.M[t-2]; + const P = opt.P[t-2]; + + let state = [initState, ...inputs.map(a => F.e(a))]; + + state = state.map((a, i) => F.add(a, C[i])); + + for (let r = 0; r < nRoundsF/2-1; r++) { + state = state.map(a => pow5(a)); + state = state.map((a, i) => F.add(a, C[(r +1)* t +i])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + } + state = state.map(a => pow5(a)); + state = state.map((a, i) => F.add(a, C[(nRoundsF/2-1 +1)* t +i])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(P[j][i], a)), F.zero) + ); + for (let r = 0; r < nRoundsP; r++) { + state[0] = pow5(state[0]); + state[0] = F.add(state[0], C[(nRoundsF/2 +1)*t + r]); + + + const s0 = state.reduce((acc, a, j) => { + return F.add(acc, F.mul(S[(t*2-1)*r+j], a)); + }, F.zero); + for (let k=1; k pow5(a)); + state = state.map((a, i) => F.add(a, C[ (nRoundsF/2 +1)*t + nRoundsP + r*t + i ])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + } + state = state.map(a => pow5(a)); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + + if (nOut == 1) { + return state[0] + } else { + return state.slice(0, nOut); + } + } + + poseidon.F = F; + return poseidon; +} + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/smt_hashes_poseidon.js + + + + +async function smt_hashes_poseidon_getHashes() { + const bn128 = await getCurveFromName("bn128", true); + const poseidon = await buildPoseidon(); + return { + hash0: function (left, right) { + return poseidon([left, right]); + }, + hash1: function(key, value) { + return poseidon([key, value, bn128.Fr.one]); + }, + F: bn128.Fr + } +} + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/smt.js + + + + +async function buildSMT(db, root) { + + const {hash0, hash1,F} = await getHashes(); + + return new SMT(db, root, hash0, hash1, F); +} + +class SMT { + + constructor(db, root, hash0, hash1, F) { + this.db = db; + this.root = root; + this.hash0 = hash0; + this.hash1 = hash1; + this.F = F; + } + + _splitBits(_key) { + const F = this.F; + const res = Scalar.bits(F.toObject(_key)); + + while (res.length<256) res.push(false); + + return res; + } + + async update(_key, _newValue) { + const F = this.F; + const key = F.e(_key); + const newValue = F.e(_newValue); + + const resFind = await this.find(key); + const res = {}; + res.oldRoot = this.root; + res.oldKey = key; + res.oldValue = resFind.foundValue; + res.newKey = key; + res.newValue = newValue; + res.siblings = resFind.siblings; + + const ins = []; + const dels = []; + + let rtOld = this.hash1(key, resFind.foundValue); + let rtNew = this.hash1(key, newValue); + ins.push([rtNew, [1, key, newValue ]]); + dels.push(rtOld); + + const keyBits = this._splitBits(key); + for (let level = resFind.siblings.length-1; level >=0; level--) { + let oldNode, newNode; + const sibling = resFind.siblings[level]; + if (keyBits[level]) { + oldNode = [sibling, rtOld]; + newNode = [sibling, rtNew]; + } else { + oldNode = [rtOld, sibling]; + newNode = [rtNew, sibling]; + } + rtOld = this.hash0(oldNode[0], oldNode[1]); + rtNew = this.hash0(newNode[0], newNode[1]); + dels.push(rtOld); + ins.push([rtNew, newNode]); + } + + res.newRoot = rtNew; + + await this.db.multiDel(dels); + await this.db.multiIns(ins); + await this.db.setRoot(rtNew); + this.root = rtNew; + + return res; + } + + async delete(_key) { + const F = this.F; + const key = F.e(_key); + + const resFind = await this.find(key); + if (!resFind.found) throw new Error("Key does not exists"); + + const res = { + siblings: [], + delKey: key, + delValue: resFind.foundValue + }; + + const dels = []; + const ins = []; + let rtOld = this.hash1(key, resFind.foundValue); + let rtNew; + dels.push(rtOld); + + let mixed; + if (resFind.siblings.length > 0) { + const record = await this.db.get(resFind.siblings[resFind.siblings.length - 1]); + if ((record.length == 3)&&(F.eq(record[0], F.one))) { + mixed = false; + res.oldKey = record[1]; + res.oldValue = record[2]; + res.isOld0 = false; + rtNew = resFind.siblings[resFind.siblings.length - 1]; + } else if (record.length == 2) { + mixed = true; + res.oldKey = key; + res.oldValue = F.zero; + res.isOld0 = true; + rtNew = F.zero; + } else { + throw new Error("Invalid node. Database corrupted"); + } + } else { + rtNew = F.zero; + res.oldKey = key; + res.oldValue = F.zero; + res.isOld0 = true; + } + + const keyBits = this._splitBits(key); + + for (let level = resFind.siblings.length-1; level >=0; level--) { + let newSibling = resFind.siblings[level]; + if ((level == resFind.siblings.length-1)&&(!res.isOld0)) { + newSibling = F.zero; + } + const oldSibling = resFind.siblings[level]; + if (keyBits[level]) { + rtOld = this.hash0(oldSibling, rtOld); + } else { + rtOld = this.hash0(rtOld, oldSibling); + } + dels.push(rtOld); + if (!F.isZero(newSibling)) { + mixed = true; + } + + if (mixed) { + res.siblings.unshift(resFind.siblings[level]); + let newNode; + if (keyBits[level]) { + newNode = [newSibling, rtNew]; + } else { + newNode = [rtNew, newSibling]; + } + rtNew = this.hash0(newNode[0], newNode[1]); + ins.push([rtNew, newNode]); + } + } + + await this.db.multiIns(ins); + await this.db.setRoot(rtNew); + this.root = rtNew; + await this.db.multiDel(dels); + + res.newRoot = rtNew; + res.oldRoot = rtOld; + + return res; + } + + async insert(_key, _value) { + const F = this.F; + const key = F.e(_key); + const value = F.e(_value); + let addedOne = false; + const res = {}; + res.oldRoot = this.root; + const newKeyBits = this._splitBits(key); + + let rtOld; + + const resFind = await this.find(key); + + if (resFind.found) throw new Error("Key already exists"); + + res.siblings = resFind.siblings; + let mixed; + + if (!resFind.isOld0) { + const oldKeyits = this._splitBits(resFind.notFoundKey); + for (let i= res.siblings.length; oldKeyits[i] == newKeyBits[i]; i++) { + res.siblings.push(F.zero); + } + rtOld = this.hash1(resFind.notFoundKey, resFind.notFoundValue); + res.siblings.push(rtOld); + addedOne = true; + mixed = false; + } else if (res.siblings.length >0) { + mixed = true; + rtOld = F.zero; + } + + const inserts = []; + const dels = []; + + let rt = this.hash1(key, value); + inserts.push([rt,[1, key, value]] ); + + for (let i=res.siblings.length-1; i>=0; i--) { + if ((i0) && (F.isZero(res.siblings[res.siblings.length-1]))) { + res.siblings.pop(); + } + res.oldKey = resFind.notFoundKey; + res.oldValue = resFind.notFoundValue; + res.newRoot = rt; + res.isOld0 = resFind.isOld0; + + + await this.db.multiIns(inserts); + await this.db.setRoot(rt); + this.root = rt; + await this.db.multiDel(dels); + + return res; + } + + async find(_key) { + const key = this.F.e(_key); + const keyBits = this._splitBits(key); + return await this._find(key, keyBits, this.root, 0); + } + + async _find(key, keyBits, root, level) { + const F = this.F; + if (typeof root === "undefined") root = this.root; + + let res; + if (F.isZero(root)) { + res = { + found: false, + siblings: [], + notFoundKey: key, + notFoundValue: F.zero, + isOld0: true + }; + return res; + } + + const record = await this.db.get(root); + + if ((record.length==3)&&(F.eq(record[0],F.one))) { + if (F.eq(record[1],key)) { + res = { + found: true, + siblings: [], + foundValue: record[2], + isOld0: false + }; + } else { + res = { + found: false, + siblings: [], + notFoundKey: record[1], + notFoundValue: record[2], + isOld0: false + }; + } + } else { + if (keyBits[level] == 0) { + res = await this._find(key, keyBits, record[0], level+1); + res.siblings.unshift(record[1]); + } else { + res = await this._find(key, keyBits, record[1], level+1); + res.siblings.unshift(record[0]); + } + } + return res; + } +} + + +async function newMemEmptyTrie() { + const {hash0, hash1,F} = await getHashes(); + const db = new SMTMemDB(F); + const rt = await db.getRoot(); + const smt = new SMT(db, rt, hash0, hash1, F); + return smt; +} + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/main.js + + + + + + +const mimc7Contract=(/* unused pure expression or super */ null && (_mimc7Contract)); + + + +const mimcSpongecontract=(/* unused pure expression or super */ null && (_mimcSpongeContract)); + + + + + +const poseidonContract=(/* unused pure expression or super */ null && (_poseidonContract)); + + + + + + + + + + +/***/ }), + +/***/ 99529: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ r: () => (/* binding */ version) +/* harmony export */ }); +/* Do NOT modify this file; see /src.ts/_admin/update-version.ts */ +/** + * The current version of Ethers. + */ +const version = "6.12.0"; +//# sourceMappingURL=_version.js.map + +/***/ }), + +/***/ 35273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + y: () => (/* binding */ AbiCoder) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/coders/abstract-coder.js +var abstract_coder = __webpack_require__(21228); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/address.js +var address = __webpack_require__(30031); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/typed.js +var typed = __webpack_require__(19353); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/address.js + + + + +/** + * @_ignore + */ +class AddressCoder extends abstract_coder/* Coder */.Ue { + constructor(localName) { + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value) { + let value = typed/* Typed */.V.dereference(_value, "string"); + try { + value = (0,address/* getAddress */.b)(value); + } + catch (error) { + return this._throwError(error.message, _value); + } + return writer.writeValue(value); + } + decode(reader) { + return (0,address/* getAddress */.b)((0,maths/* toBeHex */.up)(reader.readValue(), 20)); + } +} +//# sourceMappingURL=address.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/anonymous.js + +/** + * Clones the functionality of an existing Coder, but without a localName + * + * @_ignore + */ +class AnonymousCoder extends abstract_coder/* Coder */.Ue { + coder; + constructor(coder) { + super(coder.name, coder.type, "_", coder.dynamic); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader) { + return this.coder.decode(reader); + } +} +//# sourceMappingURL=anonymous.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/array.js + + + + +/** + * @_ignore + */ +function pack(writer, coders, values) { + let arrayValues = []; + if (Array.isArray(values)) { + arrayValues = values; + } + else if (values && typeof (values) === "object") { + let unique = {}; + arrayValues = coders.map((coder) => { + const name = coder.localName; + (0,errors/* assert */.vA)(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); + (0,errors/* assert */.vA)(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); + unique[name] = true; + return values[name]; + }); + } + else { + (0,errors/* assertArgument */.MR)(false, "invalid tuple value", "tuple", values); + } + (0,errors/* assertArgument */.MR)(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values); + let staticWriter = new abstract_coder/* Writer */.AU(); + let dynamicWriter = new abstract_coder/* Writer */.AU(); + let updateFuncs = []; + coders.forEach((coder, index) => { + let value = arrayValues[index]; + if (coder.dynamic) { + // Get current dynamic offset (for the future pointer) + let dynamicOffset = dynamicWriter.length; + // Encode the dynamic value into the dynamicWriter + coder.encode(dynamicWriter, value); + // Prepare to populate the correct offset once we are done + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset) => { + updateFunc(baseOffset + dynamicOffset); + }); + } + else { + coder.encode(staticWriter, value); + } + }); + // Backfill all the dynamic offsets, now that we know the static length + updateFuncs.forEach((func) => { func(staticWriter.length); }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +/** + * @_ignore + */ +function unpack(reader, coders) { + let values = []; + let keys = []; + // A reader anchored to this base + let baseReader = reader.subReader(0); + coders.forEach((coder) => { + let value = null; + if (coder.dynamic) { + let offset = reader.readIndex(); + let offsetReader = baseReader.subReader(offset); + try { + value = coder.decode(offsetReader); + } + catch (error) { + // Cannot recover from this + if ((0,errors/* isError */.bJ)(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + else { + try { + value = coder.decode(reader); + } + catch (error) { + // Cannot recover from this + if ((0,errors/* isError */.bJ)(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value == undefined) { + throw new Error("investigate"); + } + values.push(value); + keys.push(coder.localName || null); + }); + return abstract_coder/* Result */.Q7.fromItems(values, keys); +} +/** + * @_ignore + */ +class ArrayCoder extends abstract_coder/* Coder */.Ue { + coder; + length; + constructor(coder, length, localName) { + const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); + const dynamic = (length === -1 || coder.dynamic); + super("array", type, localName, dynamic); + (0,properties/* defineProperties */.n)(this, { coder, length }); + } + defaultValue() { + // Verifies the child coder is valid (even if the array is dynamic or 0-length) + const defaultChild = this.coder.defaultValue(); + const result = []; + for (let i = 0; i < this.length; i++) { + result.push(defaultChild); + } + return result; + } + encode(writer, _value) { + const value = typed/* Typed */.V.dereference(_value, "array"); + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count = this.length; + if (count === -1) { + count = value.length; + writer.writeValue(value.length); + } + (0,errors/* assertArgumentCount */.dd)(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); + let coders = []; + for (let i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return pack(writer, coders, value); + } + decode(reader) { + let count = this.length; + if (count === -1) { + count = reader.readIndex(); + // Check that there is *roughly* enough data to ensure + // stray random data is not being read as a length. Each + // slot requires at least 32 bytes for their value (or 32 + // bytes as a link to the data). This could use a much + // tighter bound, but we are erroring on the side of safety. + (0,errors/* assert */.vA)(count * abstract_coder/* WordSize */.Yx <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count * abstract_coder/* WordSize */.Yx, length: reader.dataLength }); + } + let coders = []; + for (let i = 0; i < count; i++) { + coders.push(new AnonymousCoder(this.coder)); + } + return unpack(reader, coders); + } +} +//# sourceMappingURL=array.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/boolean.js + + +/** + * @_ignore + */ +class BooleanCoder extends abstract_coder/* Coder */.Ue { + constructor(localName) { + super("bool", "bool", localName, false); + } + defaultValue() { + return false; + } + encode(writer, _value) { + const value = typed/* Typed */.V.dereference(_value, "bool"); + return writer.writeValue(value ? 1 : 0); + } + decode(reader) { + return !!reader.readValue(); + } +} +//# sourceMappingURL=boolean.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var utils_data = __webpack_require__(36212); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/bytes.js + + +/** + * @_ignore + */ +class DynamicBytesCoder extends abstract_coder/* Coder */.Ue { + constructor(type, localName) { + super(type, type, localName, true); + } + defaultValue() { + return "0x"; + } + encode(writer, value) { + value = (0,utils_data/* getBytesCopy */.Lm)(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader) { + return reader.readBytes(reader.readIndex(), true); + } +} +/** + * @_ignore + */ +class BytesCoder extends DynamicBytesCoder { + constructor(localName) { + super("bytes", localName); + } + decode(reader) { + return (0,utils_data/* hexlify */.c$)(super.decode(reader)); + } +} +//# sourceMappingURL=bytes.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/fixed-bytes.js + + + +/** + * @_ignore + */ +class FixedBytesCoder extends abstract_coder/* Coder */.Ue { + size; + constructor(size, localName) { + let name = "bytes" + String(size); + super(name, name, localName, false); + (0,properties/* defineProperties */.n)(this, { size }, { size: "number" }); + } + defaultValue() { + return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); + } + encode(writer, _value) { + let data = (0,utils_data/* getBytesCopy */.Lm)(typed/* Typed */.V.dereference(_value, this.type)); + if (data.length !== this.size) { + this._throwError("incorrect data length", _value); + } + return writer.writeBytes(data); + } + decode(reader) { + return (0,utils_data/* hexlify */.c$)(reader.readBytes(this.size)); + } +} +//# sourceMappingURL=fixed-bytes.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/null.js + +const Empty = new Uint8Array([]); +/** + * @_ignore + */ +class NullCoder extends abstract_coder/* Coder */.Ue { + constructor(localName) { + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); + } + return writer.writeBytes(Empty); + } + decode(reader) { + reader.readBytes(0); + return null; + } +} +//# sourceMappingURL=null.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/number.js + + + +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/** + * @_ignore + */ +class NumberCoder extends abstract_coder/* Coder */.Ue { + size; + signed; + constructor(size, signed, localName) { + const name = ((signed ? "int" : "uint") + (size * 8)); + super(name, name, localName, false); + (0,properties/* defineProperties */.n)(this, { size, signed }, { size: "number", signed: "boolean" }); + } + defaultValue() { + return 0; + } + encode(writer, _value) { + let value = (0,maths/* getBigInt */.Ab)(typed/* Typed */.V.dereference(_value, this.type)); + // Check bounds are safe for encoding + let maxUintValue = (0,maths/* mask */.dK)(BN_MAX_UINT256, abstract_coder/* WordSize */.Yx * 8); + if (this.signed) { + let bounds = (0,maths/* mask */.dK)(maxUintValue, (this.size * 8) - 1); + if (value > bounds || value < -(bounds + BN_1)) { + this._throwError("value out-of-bounds", _value); + } + value = (0,maths/* toTwos */.JJ)(value, 8 * abstract_coder/* WordSize */.Yx); + } + else if (value < BN_0 || value > (0,maths/* mask */.dK)(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value); + } + return writer.writeValue(value); + } + decode(reader) { + let value = (0,maths/* mask */.dK)(reader.readValue(), this.size * 8); + if (this.signed) { + value = (0,maths/* fromTwos */.ST)(value, this.size * 8); + } + return value; + } +} +//# sourceMappingURL=number.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/utf8.js +var utf8 = __webpack_require__(87303); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/string.js + + + +/** + * @_ignore + */ +class StringCoder extends DynamicBytesCoder { + constructor(localName) { + super("string", localName); + } + defaultValue() { + return ""; + } + encode(writer, _value) { + return super.encode(writer, (0,utf8/* toUtf8Bytes */.YW)(typed/* Typed */.V.dereference(_value, "string"))); + } + decode(reader) { + return (0,utf8/* toUtf8String */._v)(super.decode(reader)); + } +} +//# sourceMappingURL=string.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/coders/tuple.js + + + + +/** + * @_ignore + */ +class TupleCoder extends abstract_coder/* Coder */.Ue { + coders; + constructor(coders, localName) { + let dynamic = false; + const types = []; + coders.forEach((coder) => { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + const type = ("tuple(" + types.join(",") + ")"); + super("tuple", type, localName, dynamic); + (0,properties/* defineProperties */.n)(this, { coders: Object.freeze(coders.slice()) }); + } + defaultValue() { + const values = []; + this.coders.forEach((coder) => { + values.push(coder.defaultValue()); + }); + // We only output named properties for uniquely named coders + const uniqueNames = this.coders.reduce((accum, coder) => { + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + // Add named values + this.coders.forEach((coder, index) => { + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + values[name] = values[index]; + }); + return Object.freeze(values); + } + encode(writer, _value) { + const value = typed/* Typed */.V.dereference(_value, "tuple"); + return pack(writer, this.coders, value); + } + decode(reader) { + return unpack(reader, this.coders); + } +} +//# sourceMappingURL=tuple.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/fragments.js +var fragments = __webpack_require__(76124); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/abi/abi-coder.js +/** + * When sending values to or receiving values from a [[Contract]], the + * data is generally encoded using the [ABI standard](link-solc-abi). + * + * The AbiCoder provides a utility to encode values to ABI data and + * decode values from ABI data. + * + * Most of the time, developers should favour the [[Contract]] class, + * which further abstracts a lot of the finer details of ABI data. + * + * @_section api/abi/abi-coder:ABI Encoding + */ +// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI + + + + + + + + + + + + + + +// https://docs.soliditylang.org/en/v0.8.17/control-structures.html +const PanicReasons = new Map(); +PanicReasons.set(0x00, "GENERIC_PANIC"); +PanicReasons.set(0x01, "ASSERT_FALSE"); +PanicReasons.set(0x11, "OVERFLOW"); +PanicReasons.set(0x12, "DIVIDE_BY_ZERO"); +PanicReasons.set(0x21, "ENUM_RANGE_ERROR"); +PanicReasons.set(0x22, "BAD_STORAGE_DATA"); +PanicReasons.set(0x31, "STACK_UNDERFLOW"); +PanicReasons.set(0x32, "ARRAY_RANGE_ERROR"); +PanicReasons.set(0x41, "OUT_OF_MEMORY"); +PanicReasons.set(0x51, "UNINITIALIZED_FUNCTION_CALL"); +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +let defaultCoder = null; +let defaultMaxInflation = 1024; +function getBuiltinCallException(action, tx, data, abiCoder) { + let message = "missing revert data"; + let reason = null; + const invocation = null; + let revert = null; + if (data) { + message = "execution reverted"; + const bytes = (0,utils_data/* getBytes */.q5)(data); + data = (0,utils_data/* hexlify */.c$)(data); + if (bytes.length === 0) { + message += " (no data present; likely require(false) occurred"; + reason = "require(false)"; + } + else if (bytes.length % 32 !== 4) { + message += " (could not decode reason; invalid data length)"; + } + else if ((0,utils_data/* hexlify */.c$)(bytes.slice(0, 4)) === "0x08c379a0") { + // Error(string) + try { + reason = abiCoder.decode(["string"], bytes.slice(4))[0]; + revert = { + signature: "Error(string)", + name: "Error", + args: [reason] + }; + message += `: ${JSON.stringify(reason)}`; + } + catch (error) { + message += " (could not decode reason; invalid string data)"; + } + } + else if ((0,utils_data/* hexlify */.c$)(bytes.slice(0, 4)) === "0x4e487b71") { + // Panic(uint256) + try { + const code = Number(abiCoder.decode(["uint256"], bytes.slice(4))[0]); + revert = { + signature: "Panic(uint256)", + name: "Panic", + args: [code] + }; + reason = `Panic due to ${PanicReasons.get(code) || "UNKNOWN"}(${code})`; + message += `: ${reason}`; + } + catch (error) { + message += " (could not decode panic code)"; + } + } + else { + message += " (unknown custom error)"; + } + } + const transaction = { + to: (tx.to ? (0,address/* getAddress */.b)(tx.to) : null), + data: (tx.data || "0x") + }; + if (tx.from) { + transaction.from = (0,address/* getAddress */.b)(tx.from); + } + return (0,errors/* makeError */.xz)(message, "CALL_EXCEPTION", { + action, data, reason, transaction, invocation, revert + }); +} +/** + * The **AbiCoder** is a low-level class responsible for encoding JavaScript + * values into binary data and decoding binary data into JavaScript values. + */ +class AbiCoder { + #getCoder(param) { + if (param.isArray()) { + return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); + } + if (param.isTuple()) { + return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); + } + switch (param.baseType) { + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "": + return new NullCoder(param.name); + } + // u?int[0-9]* + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + (0,errors/* assertArgument */.MR)(size !== 0 && size <= 256 && (size % 8) === 0, "invalid " + match[1] + " bit length", "param", param); + return new NumberCoder(size / 8, (match[1] === "int"), param.name); + } + // bytes[0-9]+ + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + (0,errors/* assertArgument */.MR)(size !== 0 && size <= 32, "invalid bytes length", "param", param); + return new FixedBytesCoder(size, param.name); + } + (0,errors/* assertArgument */.MR)(false, "invalid type", "type", param.type); + } + /** + * Get the default values for the given %%types%%. + * + * For example, a ``uint`` is by default ``0`` and ``bool`` + * is by default ``false``. + */ + getDefaultValue(types) { + const coders = types.map((type) => this.#getCoder(fragments/* ParamType */.aX.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.defaultValue(); + } + /** + * Encode the %%values%% as the %%types%% into ABI data. + * + * @returns DataHexstring + */ + encode(types, values) { + (0,errors/* assertArgumentCount */.dd)(values.length, types.length, "types/values length mismatch"); + const coders = types.map((type) => this.#getCoder(fragments/* ParamType */.aX.from(type))); + const coder = (new TupleCoder(coders, "_")); + const writer = new abstract_coder/* Writer */.AU(); + coder.encode(writer, values); + return writer.data; + } + /** + * Decode the ABI %%data%% as the %%types%% into values. + * + * If %%loose%% decoding is enabled, then strict padding is + * not enforced. Some older versions of Solidity incorrectly + * padded event data emitted from ``external`` functions. + */ + decode(types, data, loose) { + const coders = types.map((type) => this.#getCoder(fragments/* ParamType */.aX.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.decode(new abstract_coder/* Reader */.mP(data, loose, defaultMaxInflation)); + } + static _setDefaultMaxInflation(value) { + (0,errors/* assertArgument */.MR)(typeof (value) === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value); + defaultMaxInflation = value; + } + /** + * Returns the shared singleton instance of a default [[AbiCoder]]. + * + * On the first call, the instance is created internally. + */ + static defaultAbiCoder() { + if (defaultCoder == null) { + defaultCoder = new AbiCoder(); + } + return defaultCoder; + } + /** + * Returns an ethers-compatible [[CallExceptionError]] Error for the given + * result %%data%% for the [[CallExceptionAction]] %%action%% against + * the Transaction %%tx%%. + */ + static getBuiltinCallException(action, tx, data) { + return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder()); + } +} +//# sourceMappingURL=abi-coder.js.map + +/***/ }), + +/***/ 21228: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AU: () => (/* binding */ Writer), +/* harmony export */ Q7: () => (/* binding */ Result), +/* harmony export */ Ue: () => (/* binding */ Coder), +/* harmony export */ Yx: () => (/* binding */ WordSize), +/* harmony export */ mP: () => (/* binding */ Reader) +/* harmony export */ }); +/* unused harmony export checkResultErrors */ +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27033); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36212); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(88081); + +/** + * @_ignore: + */ +const WordSize = 32; +const Padding = new Uint8Array(WordSize); +// Properties used to immediate pass through to the underlying object +// - `then` is used to detect if an object is a Promise for await +const passProperties = ["then"]; +const _guard = {}; +function throwError(name, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); + wrapped.error = error; + throw wrapped; +} +/** + * A [[Result]] is a sub-class of Array, which allows accessing any + * of its values either positionally by its index or, if keys are + * provided by its name. + * + * @_docloc: api/abi + */ +class Result extends Array { + #names; + /** + * @private + */ + constructor(...args) { + // To properly sub-class Array so the other built-in + // functions work, the constructor has to behave fairly + // well. So, in the event we are created via fromItems() + // we build the read-only Result object we want, but on + // any other input, we use the default constructor + // constructor(guard: any, items: Array, keys?: Array); + const guard = args[0]; + let items = args[1]; + let names = (args[2] || []).slice(); + let wrap = true; + if (guard !== _guard) { + items = args; + names = []; + wrap = false; + } + // Can't just pass in ...items since an array of length 1 + // is a special case in the super. + super(items.length); + items.forEach((item, index) => { this[index] = item; }); + // Find all unique keys + const nameCounts = names.reduce((accum, name) => { + if (typeof (name) === "string") { + accum.set(name, (accum.get(name) || 0) + 1); + } + return accum; + }, (new Map())); + // Remove any key thats not unique + this.#names = Object.freeze(items.map((item, index) => { + const name = names[index]; + if (name != null && nameCounts.get(name) === 1) { + return name; + } + return null; + })); + if (!wrap) { + return; + } + // A wrapped Result is immutable + Object.freeze(this); + // Proxy indices and names so we can trap deferred errors + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "string") { + // Index accessor + if (prop.match(/^[0-9]+$/)) { + const index = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .getNumber */ .WZ)(prop, "%index"); + if (index < 0 || index >= this.length) { + throw new RangeError("out of result range"); + } + const item = target[index]; + if (item instanceof Error) { + throwError(`index ${index}`, item); + } + return item; + } + // Pass important checks (like `then` for Promise) through + if (passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + const value = target[prop]; + if (value instanceof Function) { + // Make sure functions work with private variables + // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding + return function (...args) { + return value.apply((this === receiver) ? target : this, args); + }; + } + else if (!(prop in target)) { + // Possible name accessor + return target.getValue.apply((this === receiver) ? target : this, [prop]); + } + } + return Reflect.get(target, prop, receiver); + } + }); + } + /** + * Returns the Result as a normal Array. If %%deep%%, any children + * which are Result objects are also converted to a normal Array. + * + * This will throw if there are any outstanding deferred + * errors. + */ + toArray(deep) { + const result = []; + this.forEach((item, index) => { + if (item instanceof Error) { + throwError(`index ${index}`, item); + } + if (deep && item instanceof Result) { + item = item.toArray(deep); + } + result.push(item); + }); + return result; + } + /** + * Returns the Result as an Object with each name-value pair. If + * %%deep%%, any children which are Result objects are also + * converted to an Object. + * + * This will throw if any value is unnamed, or if there are + * any outstanding deferred errors. + */ + toObject(deep) { + return this.#names.reduce((accum, name, index) => { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(name != null, "value at index ${ index } unnamed", "UNSUPPORTED_OPERATION", { + operation: "toObject()" + }); + // Add values for names that don't conflict + if (!(name in accum)) { + let child = this.getValue(name); + if (deep && child instanceof Result) { + child = child.toObject(deep); + } + accum[name] = child; + } + return accum; + }, {}); + } + /** + * @_ignore + */ + slice(start, end) { + if (start == null) { + start = 0; + } + if (start < 0) { + start += this.length; + if (start < 0) { + start = 0; + } + } + if (end == null) { + end = this.length; + } + if (end < 0) { + end += this.length; + if (end < 0) { + end = 0; + } + } + if (end > this.length) { + end = this.length; + } + const result = [], names = []; + for (let i = start; i < end; i++) { + result.push(this[i]); + names.push(this.#names[i]); + } + return new Result(_guard, result, names); + } + /** + * @_ignore + */ + filter(callback, thisArg) { + const result = [], names = []; + for (let i = 0; i < this.length; i++) { + const item = this[i]; + if (item instanceof Error) { + throwError(`index ${i}`, item); + } + if (callback.call(thisArg, item, i, this)) { + result.push(item); + names.push(this.#names[i]); + } + } + return new Result(_guard, result, names); + } + /** + * @_ignore + */ + map(callback, thisArg) { + const result = []; + for (let i = 0; i < this.length; i++) { + const item = this[i]; + if (item instanceof Error) { + throwError(`index ${i}`, item); + } + result.push(callback.call(thisArg, item, i, this)); + } + return result; + } + /** + * Returns the value for %%name%%. + * + * Since it is possible to have a key whose name conflicts with + * a method on a [[Result]] or its superclass Array, or any + * JavaScript keyword, this ensures all named values are still + * accessible by name. + */ + getValue(name) { + const index = this.#names.indexOf(name); + if (index === -1) { + return undefined; + } + const value = this[index]; + if (value instanceof Error) { + throwError(`property ${JSON.stringify(name)}`, value.error); + } + return value; + } + /** + * Creates a new [[Result]] for %%items%% with each entry + * also accessible by its corresponding name in %%keys%%. + */ + static fromItems(items, keys) { + return new Result(_guard, items, keys); + } +} +/** + * Returns all errors found in a [[Result]]. + * + * Since certain errors encountered when creating a [[Result]] do + * not impact the ability to continue parsing data, they are + * deferred until they are actually accessed. Hence a faulty string + * in an Event that is never used does not impact the program flow. + * + * However, sometimes it may be useful to access, identify or + * validate correctness of a [[Result]]. + * + * @_docloc api/abi + */ +function checkResultErrors(result) { + // Find the first error (if any) + const errors = []; + const checkErrors = function (path, object) { + if (!Array.isArray(object)) { + return; + } + for (let key in object) { + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } + catch (error) { + errors.push({ path: childPath, error: error }); + } + } + }; + checkErrors([], result); + return errors; +} +function getValue(value) { + let bytes = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .toBeArray */ .c4)(value); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(bytes.length <= WordSize, "value out-of-bounds", "BUFFER_OVERRUN", { buffer: bytes, length: WordSize, offset: bytes.length }); + if (bytes.length !== WordSize) { + bytes = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .concat */ .xW)([Padding.slice(bytes.length % WordSize), bytes])); + } + return bytes; +} +/** + * @_ignore + */ +class Coder { + // The coder name: + // - address, uint256, tuple, array, etc. + name; + // The fully expanded type, including composite types: + // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. + type; + // The localName bound in the signature, in this example it is "baz": + // - tuple(address foo, uint bar) baz + localName; + // Whether this type is dynamic: + // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. + // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) + dynamic; + constructor(name, type, localName, dynamic) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_3__/* .defineProperties */ .n)(this, { name, type, localName, dynamic }, { + name: "string", type: "string", localName: "string", dynamic: "boolean" + }); + } + _throwError(message, value) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, message, this.localName, value); + } +} +/** + * @_ignore + */ +class Writer { + // An array of WordSize lengthed objects to concatenation + #data; + #dataLength; + constructor() { + this.#data = []; + this.#dataLength = 0; + } + get data() { + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .concat */ .xW)(this.#data); + } + get length() { return this.#dataLength; } + #writeData(data) { + this.#data.push(data); + this.#dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this.#writeData((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)(writer.data)); + } + // Arrayish item; pad on the right to *nearest* WordSize + writeBytes(value) { + let bytes = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)(value); + const paddingOffset = bytes.length % WordSize; + if (paddingOffset) { + bytes = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .concat */ .xW)([bytes, Padding.slice(paddingOffset)])); + } + return this.#writeData(bytes); + } + // Numeric item; pad on the left *to* WordSize + writeValue(value) { + return this.#writeData(getValue(value)); + } + // Inserts a numeric place-holder, returning a callback that can + // be used to asjust the value later + writeUpdatableValue() { + const offset = this.#data.length; + this.#data.push(Padding); + this.#dataLength += WordSize; + return (value) => { + this.#data[offset] = getValue(value); + }; + } +} +/** + * @_ignore + */ +class Reader { + // Allows incomplete unpadded data to be read; otherwise an error + // is raised if attempting to overrun the buffer. This is required + // to deal with an old Solidity bug, in which event data for + // external (not public thoguh) was tightly packed. + allowLoose; + #data; + #offset; + #bytesRead; + #parent; + #maxInflation; + constructor(data, allowLoose, maxInflation) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_3__/* .defineProperties */ .n)(this, { allowLoose: !!allowLoose }); + this.#data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)(data); + this.#bytesRead = 0; + this.#parent = null; + this.#maxInflation = (maxInflation != null) ? maxInflation : 1024; + this.#offset = 0; + } + get data() { return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .c$)(this.#data); } + get dataLength() { return this.#data.length; } + get consumed() { return this.#offset; } + get bytes() { return new Uint8Array(this.#data); } + #incrementBytesRead(count) { + if (this.#parent) { + return this.#parent.#incrementBytesRead(count); + } + this.#bytesRead += count; + // Check for excessive inflation (see: #4537) + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", { + buffer: (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)(this.#data), offset: this.#offset, + length: count, info: { + bytesRead: this.#bytesRead, + dataLength: this.dataLength + } + }); + } + #peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / WordSize) * WordSize; + if (this.#offset + alignedLength > this.#data.length) { + if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { + alignedLength = length; + } + else { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(false, "data out-of-bounds", "BUFFER_OVERRUN", { + buffer: (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytesCopy */ .Lm)(this.#data), + length: this.#data.length, + offset: this.#offset + alignedLength + }); + } + } + return this.#data.slice(this.#offset, this.#offset + alignedLength); + } + // Create a sub-reader with the same underlying data, but offset + subReader(offset) { + const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation); + reader.#parent = this; + return reader; + } + // Read bytes + readBytes(length, loose) { + let bytes = this.#peekBytes(0, length, !!loose); + this.#incrementBytesRead(length); + this.#offset += bytes.length; + // @TODO: Make sure the length..end bytes are all 0? + return bytes.slice(0, length); + } + // Read a numeric values + readValue() { + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .toBigInt */ .Dg)(this.readBytes(WordSize)); + } + readIndex() { + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .toNumber */ .Ro)(this.readBytes(WordSize)); + } +} +//# sourceMappingURL=abstract-coder.js.map + +/***/ }), + +/***/ 76124: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ FK: () => (/* binding */ Fragment), +/* harmony export */ Pw: () => (/* binding */ ConstructorFragment), +/* harmony export */ Zp: () => (/* binding */ EventFragment), +/* harmony export */ aX: () => (/* binding */ ParamType), +/* harmony export */ bp: () => (/* binding */ ErrorFragment), +/* harmony export */ hc: () => (/* binding */ FunctionFragment) +/* harmony export */ }); +/* unused harmony exports NamedFragment, FallbackFragment, StructFragment */ +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27033); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88081); +/* harmony import */ var _hash_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(38264); +/** + * A fragment is a single item from an ABI, which may represent any of: + * + * - [Functions](FunctionFragment) + * - [Events](EventFragment) + * - [Constructors](ConstructorFragment) + * - Custom [Errors](ErrorFragment) + * - [Fallback or Receive](FallbackFragment) functions + * + * @_subsection api/abi/abi-coder:Fragments [about-fragments] + */ + + +; +// [ "a", "b" ] => { "a": 1, "b": 1 } +function setify(items) { + const result = new Set(); + items.forEach((k) => result.add(k)); + return Object.freeze(result); +} +const _kwVisibDeploy = "external public payable override"; +const KwVisibDeploy = setify(_kwVisibDeploy.split(" ")); +// Visibility Keywords +const _kwVisib = "constant external internal payable private public pure view override"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event fallback function receive struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +// All Keywords +const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); +const Keywords = setify(_keywords.split(" ")); +// Single character tokens +const SimpleTokens = { + "(": "OPEN_PAREN", ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET", + ",": "COMMA", "@": "AT" +}; +// Parser regexes to consume the next token +const regexWhitespacePrefix = new RegExp("^(\\s*)"); +const regexNumberPrefix = new RegExp("^([0-9]+)"); +const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +// Parser regexs to check validity +const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"); +class TokenString { + #offset; + #tokens; + get offset() { return this.#offset; } + get length() { return this.#tokens.length - this.#offset; } + constructor(tokens) { + this.#offset = 0; + this.#tokens = tokens.slice(); + } + clone() { return new TokenString(this.#tokens); } + reset() { this.#offset = 0; } + #subTokenString(from = 0, to = 0) { + return new TokenString(this.#tokens.slice(from, to).map((t) => { + return Object.freeze(Object.assign({}, t, { + match: (t.match - from), + linkBack: (t.linkBack - from), + linkNext: (t.linkNext - from), + })); + })); + } + // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + // Pops and returns the value of the next token if it is `type`; throws if out of tokens + popType(type) { + if (this.peek().type !== type) { + const top = this.peek(); + throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`); + } + return this.pop().text; + } + // Pops and returns a "(" TOKENS ")" + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = this.#subTokenString(this.#offset + 1, top.match + 1); + this.#offset = top.match + 1; + return result; + } + // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while (this.#offset < top.match - 1) { + const link = this.peek().linkNext; + result.push(this.#subTokenString(this.#offset + 1, link)); + this.#offset = link; + } + this.#offset = top.match + 1; + return result; + } + // Returns the top Token, throwing if out of tokens + peek() { + if (this.#offset >= this.#tokens.length) { + throw new Error("out-of-bounds"); + } + return this.#tokens[this.#offset]; + } + // Returns the next value, if it is a keyword in `allowed` + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return (top != null && allowed.has(top)) ? top : null; + } + // Returns the value of the next token if it is `type` + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return (top.type === type) ? top.text : null; + } + // Returns the next token; throws if out of tokens + pop() { + const result = this.peek(); + this.#offset++; + return result; + } + toString() { + const tokens = []; + for (let i = this.#offset; i < this.#tokens.length; i++) { + const token = this.#tokens[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +} +function lex(text) { + const tokens = []; + const throwError = (message) => { + const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset = 0; + while (offset < text.length) { + // Strip off any leading whitespace + let cur = text.substring(offset); + let match = cur.match(regexWhitespacePrefix); + if (match) { + offset += match[1].length; + cur = text.substring(offset); + } + const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 }; + tokens.push(token); + let type = (SimpleTokens[cur[0]] || ""); + if (type) { + token.type = type; + token.text = cur[0]; + offset++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } + else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError("no matching open bracket"); + } + token.match = brackets.pop(); + (tokens[token.match]).match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + } + else if (type === "COMMA") { + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } + else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } + else if (type === "CLOSE_BRACKET") { + // Remove the CLOSE_BRACKET + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + (tokens[tokens.length - 1]).value = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .getNumber */ .WZ)(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + (tokens[tokens.length - 1]).text += suffix; + } + continue; + } + match = cur.match(regexIdPrefix); + if (match) { + token.text = match[1]; + offset += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumberPrefix); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); + } + return new TokenString(tokens.map((t) => Object.freeze(t))); +} +// Check only one of `allowed` is in `set` +function allowSingle(set, allowed) { + let included = []; + for (const key in allowed.keys()) { + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +// Functions to process a Solidity Signature TokenString from left-to-right for... +// ...the name with an optional type, returning the name +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +// ...all keywords matching allowed, returning the keywords +function consumeKeywords(tokens, allowed) { + const keywords = new Set(); + while (true) { + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || (allowed && !allowed.has(keyword))) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +// ...all visibility keywords, returning the coalesced mutability +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + // Detect conflicting modifiers + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + // Process mutability states + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + // Process legacy `constant` last + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +// ...a parameter list, returning the ParamType list +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t) => ParamType.from(t, allowIndexed)); +} +// ...a gas limit, returning a BigNumber or null if none +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .getBigInt */ .Ab)(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(match, "invalid type", "type", type); + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + // bytesXX + const length = parseInt(match[2]); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(length !== 0 && length <= 32, "invalid bytes length", "type", type); + } + else if (match[3]) { + // intXX or uintXX + const size = parseInt(match[3]); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(size !== 0 && size <= 256 && (size % 8) === 0, "invalid numeric width", "type", type); + } + return type; +} +// Make the Fragment constructors effectively private +const _guard = {}; +const internal = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +const ErrorFragmentInternal = "_ErrorInternal"; +const EventFragmentInternal = "_EventInternal"; +const ConstructorFragmentInternal = "_ConstructorInternal"; +const FallbackFragmentInternal = "_FallbackInternal"; +const FunctionFragmentInternal = "_FunctionInternal"; +const StructFragmentInternal = "_StructInternal"; +/** + * Each input and output of a [[Fragment]] is an Array of **ParamType**. + */ +class ParamType { + /** + * The local name of the parameter (or ``""`` if unbound) + */ + name; + /** + * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``, + * ``"uint256[3][]"``) + */ + type; + /** + * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``) + */ + baseType; + /** + * True if the parameters is indexed. + * + * For non-indexable types this is ``null``. + */ + indexed; + /** + * The components for the tuple. + * + * For non-tuple types this is ``null``. + */ + components; + /** + * The array length, or ``-1`` for dynamic-lengthed arrays. + * + * For non-array types this is ``null``. + */ + arrayLength; + /** + * The type of each child in the array. + * + * For non-array types this is ``null``. + */ + arrayChildren; + /** + * @private + */ + constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertPrivate */ .gk)(guard, _guard, "ParamType"); + Object.defineProperty(this, internal, { value: ParamTypeInternal }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); + } + } + else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); + } + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } + else if (components != null) { + throw new Error(""); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { + name, type, baseType, indexed, components, arrayLength, arrayChildren + }); + } + /** + * Return a string representation of this type. + * + * For example, + * + * ``sighash" => "(uint256,address)"`` + * + * ``"minimal" => "tuple(uint256,address) indexed"`` + * + * ``"full" => "tuple(uint256 foo, address bar) indexed baz"`` + */ + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + const name = this.name || ""; + if (this.isArray()) { + const result = JSON.parse(this.arrayChildren.format("json")); + result.name = name; + result.type += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`; + return JSON.stringify(result); + } + const result = { + type: ((this.baseType === "tuple") ? "tuple" : this.type), + name + }; + if (typeof (this.indexed) === "boolean") { + result.indexed = this.indexed; + } + if (this.isTuple()) { + result.components = this.components.map((c) => JSON.parse(c.format(format))); + } + return JSON.stringify(result); + } + let result = ""; + // Array + if (this.isArray()) { + result += this.arrayChildren.format(format); + result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`; + } + else { + if (this.isTuple()) { + result += "(" + this.components.map((comp) => comp.format(format)).join((format === "full") ? ", " : ",") + ")"; + } + else { + result += this.type; + } + } + if (format !== "sighash") { + if (this.indexed === true) { + result += " indexed"; + } + if (format === "full" && this.name) { + result += " " + this.name; + } + } + return result; + } + /** + * Returns true if %%this%% is an Array type. + * + * This provides a type gaurd ensuring that [[arrayChildren]] + * and [[arrayLength]] are non-null. + */ + isArray() { + return (this.baseType === "array"); + } + /** + * Returns true if %%this%% is a Tuple type. + * + * This provides a type gaurd ensuring that [[components]] + * is non-null. + */ + isTuple() { + return (this.baseType === "tuple"); + } + /** + * Returns true if %%this%% is an Indexable type. + * + * This provides a type gaurd ensuring that [[indexed]] + * is non-null. + */ + isIndexable() { + return (this.indexed != null); + } + /** + * Walks the **ParamType** with %%value%%, calling %%process%% + * on each type, destructing the %%value%% recursively. + */ + walk(value, process) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v) => (_this.arrayChildren.walk(v, process))); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invalid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v, i) => (_this.components[i].walk(v, process))); + } + return process(this.type, value); + } + #walkAsync(promises, value, process, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result = value.slice(); + result.forEach((value, index) => { + childType.#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + if (this.isTuple()) { + const components = this.components; + // Convert the object into an array + let result; + if (Array.isArray(value)) { + result = value.slice(); + } + else { + if (value == null || typeof (value) !== "object") { + throw new Error("invalid tuple value"); + } + result = components.map((param) => { + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (result.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result.forEach((value, index) => { + components[index].#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + const result = process(this.type, value); + if (result.then) { + promises.push((async function () { setValue(await result); })()); + } + else { + setValue(result); + } + } + /** + * Walks the **ParamType** with %%value%%, asynchronously calling + * %%process%% on each type, destructing the %%value%% recursively. + * + * This can be used to resolve ENS naes by walking and resolving each + * ``"address"`` type. + */ + async walkAsync(value, process) { + const promises = []; + const result = [value]; + this.#walkAsync(promises, value, process, (value) => { + result[0] = value; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + /** + * Creates a new **ParamType** for %%obj%%. + * + * If %%allowIndexed%% then the ``indexed`` keyword is permitted, + * otherwise the ``indexed`` keyword will throw an error. + */ + static from(obj, allowIndexed) { + if (ParamType.isParamType(obj)) { + return obj; + } + if (typeof (obj) === "string") { + try { + return ParamType.from(lex(obj), allowIndexed); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid param type", "obj", obj); + } + } + else if (obj instanceof TokenString) { + let type = "", baseType = ""; + let comps = null; + if (consumeKeywords(obj, setify(["tuple"])).has("tuple") || obj.peekType("OPEN_PAREN")) { + // Tuple + baseType = "tuple"; + comps = obj.popParams().map((t) => ParamType.from(t)); + type = `tuple(${comps.map((c) => c.format()).join(",")})`; + } + else { + // Normal + type = verifyBasicType(obj.popType("TYPE")); + baseType = type; + } + // Check for Array + let arrayChildren = null; + let arrayLength = null; + while (obj.length && obj.peekType("BRACKET")) { + const bracket = obj.pop(); //arrays[i]; + arrayChildren = new ParamType(_guard, "", type, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type += bracket.text; + baseType = "array"; + comps = null; + } + let indexed = null; + const keywords = consumeKeywords(obj, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed = true; + } + const name = (obj.peekType("ID") ? obj.pop().text : ""); + if (obj.length) { + throw new Error("leftover tokens"); + } + return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren); + } + const name = obj.name; + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(!name || (typeof (name) === "string" && name.match(regexId)), "invalid name", "obj.name", name); + let indexed = obj.indexed; + if (indexed != null) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed); + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = parseInt(arrayMatch[2] || "-1"); + const arrayChildren = ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new ParamType(_guard, name || "", type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type === "tuple" || type.startsWith("tuple(" /* fix: ) */) || type.startsWith("(" /* fix: ) */)) { + const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null; + const tuple = new ParamType(_guard, name || "", type, "tuple", indexed, comps, null, null); + // @TODO: use lexer to validate and normalize type + return tuple; + } + type = verifyBasicType(obj.type); + return new ParamType(_guard, name || "", type, type, indexed, null, null, null); + } + /** + * Returns true if %%value%% is a **ParamType**. + */ + static isParamType(value) { + return (value && value[internal] === ParamTypeInternal); + } +} +/** + * An abstract class to represent An individual fragment from a parse ABI. + */ +class Fragment { + /** + * The type of the fragment. + */ + type; + /** + * The inputs for the fragment. + */ + inputs; + /** + * @private + */ + constructor(guard, type, inputs) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertPrivate */ .gk)(guard, _guard, "Fragment"); + inputs = Object.freeze(inputs.slice()); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { type, inputs }); + } + /** + * Creates a new **Fragment** for %%obj%%, wich can be any supported + * ABI frgament type. + */ + static from(obj) { + if (typeof (obj) === "string") { + // Try parsing JSON... + try { + Fragment.from(JSON.parse(obj)); + } + catch (e) { } + // ...otherwise, use the human-readable lexer + return Fragment.from(lex(obj)); + } + if (obj instanceof TokenString) { + // Human-readable ABI (already lexed) + const type = obj.peekKeyword(KwTypes); + switch (type) { + case "constructor": return ConstructorFragment.from(obj); + case "error": return ErrorFragment.from(obj); + case "event": return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": return FunctionFragment.from(obj); + case "struct": return StructFragment.from(obj); + } + } + else if (typeof (obj) === "object") { + // JSON ABI + switch (obj.type) { + case "constructor": return ConstructorFragment.from(obj); + case "error": return ErrorFragment.from(obj); + case "event": return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": return FunctionFragment.from(obj); + case "struct": return StructFragment.from(obj); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", { + operation: "Fragment.from" + }); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "unsupported frgament object", "obj", obj); + } + /** + * Returns true if %%value%% is a [[ConstructorFragment]]. + */ + static isConstructor(value) { + return ConstructorFragment.isFragment(value); + } + /** + * Returns true if %%value%% is an [[ErrorFragment]]. + */ + static isError(value) { + return ErrorFragment.isFragment(value); + } + /** + * Returns true if %%value%% is an [[EventFragment]]. + */ + static isEvent(value) { + return EventFragment.isFragment(value); + } + /** + * Returns true if %%value%% is a [[FunctionFragment]]. + */ + static isFunction(value) { + return FunctionFragment.isFragment(value); + } + /** + * Returns true if %%value%% is a [[StructFragment]]. + */ + static isStruct(value) { + return StructFragment.isFragment(value); + } +} +/** + * An abstract class to represent An individual fragment + * which has a name from a parse ABI. + */ +class NamedFragment extends Fragment { + /** + * The name of the fragment. + */ + name; + /** + * @private + */ + constructor(guard, type, name, inputs) { + super(guard, type, inputs); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(typeof (name) === "string" && name.match(regexId), "invalid identifier", "name", name); + inputs = Object.freeze(inputs.slice()); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { name }); + } +} +function joinParams(format, params) { + return "(" + params.map((p) => p.format(format)).join((format === "full") ? ", " : ",") + ")"; +} +/** + * A Fragment which represents a //Custom Error//. + */ +class ErrorFragment extends NamedFragment { + /** + * @private + */ + constructor(guard, name, inputs) { + super(guard, "error", name, inputs); + Object.defineProperty(this, internal, { value: ErrorFragmentInternal }); + } + /** + * The Custom Error selector. + */ + get selector() { + return (0,_hash_index_js__WEBPACK_IMPORTED_MODULE_3__.id)(this.format("sighash")).substring(0, 10); + } + /** + * Returns a string representation of this fragment as %%format%%. + */ + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input) => JSON.parse(input.format(format))), + }); + } + const result = []; + if (format !== "sighash") { + result.push("error"); + } + result.push(this.name + joinParams(format, this.inputs)); + return result.join(" "); + } + /** + * Returns a new **ErrorFragment** for %%obj%%. + */ + static from(obj) { + if (ErrorFragment.isFragment(obj)) { + return obj; + } + if (typeof (obj) === "string") { + return ErrorFragment.from(lex(obj)); + } + else if (obj instanceof TokenString) { + const name = consumeName("error", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new ErrorFragment(_guard, name, inputs); + } + return new ErrorFragment(_guard, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); + } + /** + * Returns ``true`` and provides a type guard if %%value%% is an + * **ErrorFragment**. + */ + static isFragment(value) { + return (value && value[internal] === ErrorFragmentInternal); + } +} +/** + * A Fragment which represents an Event. + */ +class EventFragment extends NamedFragment { + /** + * Whether this event is anonymous. + */ + anonymous; + /** + * @private + */ + constructor(guard, name, inputs, anonymous) { + super(guard, "event", name, inputs); + Object.defineProperty(this, internal, { value: EventFragmentInternal }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { anonymous }); + } + /** + * The Event topic hash. + */ + get topicHash() { + return (0,_hash_index_js__WEBPACK_IMPORTED_MODULE_3__.id)(this.format("sighash")); + } + /** + * Returns a string representation of this event as %%format%%. + */ + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = []; + if (format !== "sighash") { + result.push("event"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== "sighash" && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); + } + /** + * Return the topic hash for an event with %%name%% and %%params%%. + */ + static getTopicHash(name, params) { + params = (params || []).map((p) => ParamType.from(p)); + const fragment = new EventFragment(_guard, name, params, false); + return fragment.topicHash; + } + /** + * Returns a new **EventFragment** for %%obj%%. + */ + static from(obj) { + if (EventFragment.isFragment(obj)) { + return obj; + } + if (typeof (obj) === "string") { + try { + return EventFragment.from(lex(obj)); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid event fragment", "obj", obj); + } + } + else if (obj instanceof TokenString) { + const name = consumeName("event", obj); + const inputs = consumeParams(obj, true); + const anonymous = !!consumeKeywords(obj, setify(["anonymous"])).has("anonymous"); + consumeEoi(obj); + return new EventFragment(_guard, name, inputs, anonymous); + } + return new EventFragment(_guard, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous); + } + /** + * Returns ``true`` and provides a type guard if %%value%% is an + * **EventFragment**. + */ + static isFragment(value) { + return (value && value[internal] === EventFragmentInternal); + } +} +/** + * A Fragment which represents a constructor. + */ +class ConstructorFragment extends Fragment { + /** + * Whether the constructor can receive an endowment. + */ + payable; + /** + * The recommended gas limit for deployment or ``null``. + */ + gas; + /** + * @private + */ + constructor(guard, type, inputs, payable, gas) { + super(guard, type, inputs); + Object.defineProperty(this, internal, { value: ConstructorFragmentInternal }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { payable, gas }); + } + /** + * Returns a string representation of this constructor as %%format%%. + */ + format(format) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assert */ .vA)(format != null && format !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" }); + if (format === "json") { + return JSON.stringify({ + type: "constructor", + stateMutability: (this.payable ? "payable" : "undefined"), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = [`constructor${joinParams(format, this.inputs)}`]; + if (this.payable) { + result.push("payable"); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); + } + /** + * Returns a new **ConstructorFragment** for %%obj%%. + */ + static from(obj) { + if (ConstructorFragment.isFragment(obj)) { + return obj; + } + if (typeof (obj) === "string") { + try { + return ConstructorFragment.from(lex(obj)); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid constuctor fragment", "obj", obj); + } + } + else if (obj instanceof TokenString) { + consumeKeywords(obj, setify(["constructor"])); + const inputs = consumeParams(obj); + const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable"); + const gas = consumeGas(obj); + consumeEoi(obj); + return new ConstructorFragment(_guard, "constructor", inputs, payable, gas); + } + return new ConstructorFragment(_guard, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, (obj.gas != null) ? obj.gas : null); + } + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **ConstructorFragment**. + */ + static isFragment(value) { + return (value && value[internal] === ConstructorFragmentInternal); + } +} +/** + * A Fragment which represents a method. + */ +class FallbackFragment extends Fragment { + /** + * If the function can be sent value during invocation. + */ + payable; + constructor(guard, inputs, payable) { + super(guard, "fallback", inputs); + Object.defineProperty(this, internal, { value: FallbackFragmentInternal }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { payable }); + } + /** + * Returns a string representation of this fallback as %%format%%. + */ + format(format) { + const type = ((this.inputs.length === 0) ? "receive" : "fallback"); + if (format === "json") { + const stateMutability = (this.payable ? "payable" : "nonpayable"); + return JSON.stringify({ type, stateMutability }); + } + return `${type}()${this.payable ? " payable" : ""}`; + } + /** + * Returns a new **FallbackFragment** for %%obj%%. + */ + static from(obj) { + if (FallbackFragment.isFragment(obj)) { + return obj; + } + if (typeof (obj) === "string") { + try { + return FallbackFragment.from(lex(obj)); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid fallback fragment", "obj", obj); + } + } + else if (obj instanceof TokenString) { + const errorObj = obj.toString(); + const topIsValid = obj.peekKeyword(setify(["fallback", "receive"])); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(topIsValid, "type must be fallback or receive", "obj", errorObj); + const type = obj.popKeyword(setify(["fallback", "receive"])); + // receive() + if (type === "receive") { + const inputs = consumeParams(obj); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(inputs.length === 0, `receive cannot have arguments`, "obj.inputs", inputs); + consumeKeywords(obj, setify(["payable"])); + consumeEoi(obj); + return new FallbackFragment(_guard, [], true); + } + // fallback() [payable] + // fallback(bytes) [payable] returns (bytes) + let inputs = consumeParams(obj); + if (inputs.length) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i) => i.format("minimal")).join(", ")); + } + else { + inputs = [ParamType.from("bytes")]; + } + const mutability = consumeMutability(obj); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability); + if (consumeKeywords(obj, setify(["returns"])).has("returns")) { + const outputs = consumeParams(obj); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i) => i.format("minimal")).join(", ")); + } + consumeEoi(obj); + return new FallbackFragment(_guard, inputs, mutability === "payable"); + } + if (obj.type === "receive") { + return new FallbackFragment(_guard, [], true); + } + if (obj.type === "fallback") { + const inputs = [ParamType.from("bytes")]; + const payable = (obj.stateMutability === "payable"); + return new FallbackFragment(_guard, inputs, payable); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid fallback description", "obj", obj); + } + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **FallbackFragment**. + */ + static isFragment(value) { + return (value && value[internal] === FallbackFragmentInternal); + } +} +/** + * A Fragment which represents a method. + */ +class FunctionFragment extends NamedFragment { + /** + * If the function is constant (e.g. ``pure`` or ``view`` functions). + */ + constant; + /** + * The returned types for the result of calling this function. + */ + outputs; + /** + * The state mutability (e.g. ``payable``, ``nonpayable``, ``view`` + * or ``pure``) + */ + stateMutability; + /** + * If the function can be sent value during invocation. + */ + payable; + /** + * The recommended gas limit to send when calling this function. + */ + gas; + /** + * @private + */ + constructor(guard, name, stateMutability, inputs, outputs, gas) { + super(guard, "function", name, inputs); + Object.defineProperty(this, internal, { value: FunctionFragmentInternal }); + outputs = Object.freeze(outputs.slice()); + const constant = (stateMutability === "view" || stateMutability === "pure"); + const payable = (stateMutability === "payable"); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .defineProperties */ .n)(this, { constant, gas, outputs, payable, stateMutability }); + } + /** + * The Function selector. + */ + get selector() { + return (0,_hash_index_js__WEBPACK_IMPORTED_MODULE_3__.id)(this.format("sighash")).substring(0, 10); + } + /** + * Returns a string representation of this function as %%format%%. + */ + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))), + outputs: this.outputs.map((o) => JSON.parse(o.format(format))), + }); + } + const result = []; + if (format !== "sighash") { + result.push("function"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== "sighash") { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); + } + /** + * Return the selector for a function with %%name%% and %%params%%. + */ + static getSelector(name, params) { + params = (params || []).map((p) => ParamType.from(p)); + const fragment = new FunctionFragment(_guard, name, "view", params, [], null); + return fragment.selector; + } + /** + * Returns a new **FunctionFragment** for %%obj%%. + */ + static from(obj) { + if (FunctionFragment.isFragment(obj)) { + return obj; + } + if (typeof (obj) === "string") { + try { + return FunctionFragment.from(lex(obj)); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid function fragment", "obj", obj); + } + } + else if (obj instanceof TokenString) { + const name = consumeName("function", obj); + const inputs = consumeParams(obj); + const mutability = consumeMutability(obj); + let outputs = []; + if (consumeKeywords(obj, setify(["returns"])).has("returns")) { + outputs = consumeParams(obj); + } + const gas = consumeGas(obj); + consumeEoi(obj); + return new FunctionFragment(_guard, name, mutability, inputs, outputs, gas); + } + let stateMutability = obj.stateMutability; + // Use legacy Solidity ABI logic if stateMutability is missing + if (stateMutability == null) { + stateMutability = "payable"; + if (typeof (obj.constant) === "boolean") { + stateMutability = "view"; + if (!obj.constant) { + stateMutability = "payable"; + if (typeof (obj.payable) === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; + } + } + } + else if (typeof (obj.payable) === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; + } + } + // @TODO: verifyState for stateMutability (e.g. throw if + // payable: false but stateMutability is "nonpayable") + return new FunctionFragment(_guard, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], (obj.gas != null) ? obj.gas : null); + } + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **FunctionFragment**. + */ + static isFragment(value) { + return (value && value[internal] === FunctionFragmentInternal); + } +} +/** + * A Fragment which represents a structure. + */ +class StructFragment extends NamedFragment { + /** + * @private + */ + constructor(guard, name, inputs) { + super(guard, "struct", name, inputs); + Object.defineProperty(this, internal, { value: StructFragmentInternal }); + } + /** + * Returns a string representation of this struct as %%format%%. + */ + format() { + throw new Error("@TODO"); + } + /** + * Returns a new **StructFragment** for %%obj%%. + */ + static from(obj) { + if (typeof (obj) === "string") { + try { + return StructFragment.from(lex(obj)); + } + catch (error) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(false, "invalid struct fragment", "obj", obj); + } + } + else if (obj instanceof TokenString) { + const name = consumeName("struct", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new StructFragment(_guard, name, inputs); + } + return new StructFragment(_guard, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); + } + // @TODO: fix this return type + /** + * Returns ``true`` and provides a type guard if %%value%% is a + * **StructFragment**. + */ + static isFragment(value) { + return (value && value[internal] === StructFragmentInternal); + } +} +//# sourceMappingURL=fragments.js.map + +/***/ }), + +/***/ 73622: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ KA: () => (/* binding */ Interface) +/* harmony export */ }); +/* unused harmony exports LogDescription, TransactionDescription, ErrorDescription, Indexed */ +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(15539); +/* harmony import */ var _hash_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(38264); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88081); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(36212); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(27033); +/* harmony import */ var _abi_coder_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35273); +/* harmony import */ var _coders_abstract_coder_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(21228); +/* harmony import */ var _fragments_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76124); +/* harmony import */ var _typed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(19353); +/* provided dependency */ var console = __webpack_require__(96763); +/** + * The Interface class is a low-level class that accepts an + * ABI and provides all the necessary functionality to encode + * and decode paramaters to and results from methods, events + * and errors. + * + * It also provides several convenience methods to automatically + * search and find matching transactions and events to parse them. + * + * @_subsection api/abi:Interfaces [interfaces] + */ + + + + + + + + +/** + * When using the [[Interface-parseLog]] to automatically match a Log to its event + * for parsing, a **LogDescription** is returned. + */ +class LogDescription { + /** + * The matching fragment for the ``topic0``. + */ + fragment; + /** + * The name of the Event. + */ + name; + /** + * The full Event signature. + */ + signature; + /** + * The topic hash for the Event. + */ + topic; + /** + * The arguments passed into the Event with ``emit``. + */ + args; + /** + * @_ignore: + */ + constructor(fragment, topic, args) { + const name = fragment.name, signature = fragment.format(); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + fragment, name, signature, topic, args + }); + } +} +/** + * When using the [[Interface-parseTransaction]] to automatically match + * a transaction data to its function for parsing, + * a **TransactionDescription** is returned. + */ +class TransactionDescription { + /** + * The matching fragment from the transaction ``data``. + */ + fragment; + /** + * The name of the Function from the transaction ``data``. + */ + name; + /** + * The arguments passed to the Function from the transaction ``data``. + */ + args; + /** + * The full Function signature from the transaction ``data``. + */ + signature; + /** + * The selector for the Function from the transaction ``data``. + */ + selector; + /** + * The ``value`` (in wei) from the transaction. + */ + value; + /** + * @_ignore: + */ + constructor(fragment, selector, args, value) { + const name = fragment.name, signature = fragment.format(); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + fragment, name, args, signature, selector, value + }); + } +} +/** + * When using the [[Interface-parseError]] to automatically match an + * error for a call result for parsing, an **ErrorDescription** is returned. + */ +class ErrorDescription { + /** + * The matching fragment. + */ + fragment; + /** + * The name of the Error. + */ + name; + /** + * The arguments passed to the Error with ``revert``. + */ + args; + /** + * The full Error signature. + */ + signature; + /** + * The selector for the Error. + */ + selector; + /** + * @_ignore: + */ + constructor(fragment, selector, args) { + const name = fragment.name, signature = fragment.format(); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + fragment, name, args, signature, selector + }); + } +} +/** + * An **Indexed** is used as a value when a value that does not + * fit within a topic (i.e. not a fixed-length, 32-byte type). It + * is the ``keccak256`` of the value, and used for types such as + * arrays, tuples, bytes and strings. + */ +class Indexed { + /** + * The ``keccak256`` of the value logged. + */ + hash; + /** + * @_ignore: + */ + _isIndexed; + /** + * Returns ``true`` if %%value%% is an **Indexed**. + * + * This provides a Type Guard for property access. + */ + static isIndexed(value) { + return !!(value && value._isIndexed); + } + /** + * @_ignore: + */ + constructor(hash) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { hash, _isIndexed: true }); + } +} +// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require +const PanicReasons = { + "0": "generic panic", + "1": "assert(false)", + "17": "arithmetic overflow", + "18": "division or modulo by zero", + "33": "enum overflow", + "34": "invalid encoded storage byte array accessed", + "49": "out-of-bounds array access; popping on an empty array", + "50": "out-of-bounds access of an array or bytesN", + "65": "out of memory", + "81": "uninitialized function", +}; +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: ["string"], + reason: (message) => { + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: ["uint256"], + reason: (code) => { + let reason = "unknown panic code"; + if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { + reason = PanicReasons[code.toString()]; + } + return `reverted with panic code 0x${code.toString(16)} (${reason})`; + } + } +}; +/** + * An Interface abstracts many of the low-level details for + * encoding and decoding the data on the blockchain. + * + * An ABI provides information on how to encode data to send to + * a Contract, how to decode the results and events and how to + * interpret revert errors. + * + * The ABI can be specified by [any supported format](InterfaceAbi). + */ +class Interface { + /** + * All the Contract ABI members (i.e. methods, events, errors, etc). + */ + fragments; + /** + * The Contract constructor. + */ + deploy; + /** + * The Fallback method, if any. + */ + fallback; + /** + * If receiving ether is supported. + */ + receive; + #errors; + #events; + #functions; + // #structs: Map; + #abiCoder; + /** + * Create a new Interface for the %%fragments%%. + */ + constructor(fragments) { + let abi = []; + if (typeof (fragments) === "string") { + abi = JSON.parse(fragments); + } + else { + abi = fragments; + } + this.#functions = new Map(); + this.#errors = new Map(); + this.#events = new Map(); + // this.#structs = new Map(); + const frags = []; + for (const a of abi) { + try { + frags.push(_fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .Fragment */ .FK.from(a)); + } + catch (error) { + console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`, error.message); + } + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + fragments: Object.freeze(frags) + }); + let fallback = null; + let receive = false; + this.#abiCoder = this.getAbiCoder(); + // Add all fragments by their signature + this.fragments.forEach((fragment, index) => { + let bucket; + switch (fragment.type) { + case "constructor": + if (this.deploy) { + console.log("duplicate definition - constructor"); + return; + } + //checkNames(fragment, "input", fragment.inputs); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { deploy: fragment }); + return; + case "fallback": + if (fragment.inputs.length === 0) { + receive = true; + } + else { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(!fallback || fragment.payable !== fallback.payable, "conflicting fallback fragments", `fragments[${index}]`, fragment); + fallback = fragment; + receive = fallback.payable; + } + return; + case "function": + //checkNames(fragment, "input", fragment.inputs); + //checkNames(fragment, "output", (fragment).outputs); + bucket = this.#functions; + break; + case "event": + //checkNames(fragment, "input", fragment.inputs); + bucket = this.#events; + break; + case "error": + bucket = this.#errors; + break; + default: + return; + } + // Two identical entries; ignore it + const signature = fragment.format(); + if (bucket.has(signature)) { + return; + } + bucket.set(signature, fragment); + }); + // If we do not have a constructor add a default + if (!this.deploy) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + deploy: _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ConstructorFragment */ .Pw.from("constructor()") + }); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { fallback, receive }); + } + /** + * Returns the entire Human-Readable ABI, as an array of + * signatures, optionally as %%minimal%% strings, which + * removes parameter names and unneceesary spaces. + */ + format(minimal) { + const format = (minimal ? "minimal" : "full"); + const abi = this.fragments.map((f) => f.format(format)); + return abi; + } + /** + * Return the JSON-encoded ABI. This is the format Solidiy + * returns. + */ + formatJson() { + const abi = this.fragments.map((f) => f.format("json")); + // We need to re-bundle the JSON fragments a bit + return JSON.stringify(abi.map((j) => JSON.parse(j))); + } + /** + * The ABI coder that will be used to encode and decode binary + * data. + */ + getAbiCoder() { + return _abi_coder_js__WEBPACK_IMPORTED_MODULE_3__/* .AbiCoder */ .y.defaultAbiCoder(); + } + // Find a function definition by any means necessary (unless it is ambiguous) + #getFunction(key, values, forceUnique) { + // Selector + if ((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .isHexString */ .Lo)(key)) { + const selector = key.toLowerCase(); + for (const fragment of this.#functions.values()) { + if (selector === fragment.selector) { + return fragment; + } + } + return null; + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#functions) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + const lastValue = (values.length > 0) ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (_typed_js__WEBPACK_IMPORTED_MODULE_5__/* .Typed */ .V.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + // Remove all matches that don't have a compatible length. The args + // may contain an overrides, so the match may have n or n - 1 parameters + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!_typed_js__WEBPACK_IMPORTED_MODULE_5__/* .Typed */ .V.isTyped(values[j])) { + continue; + } + // We are past the inputs + if (j >= inputs.length) { + if (values[j].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + // We found a single matching signature with an overrides, but the + // last value is something that cannot possibly be an options + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") { + matching.splice(0, 1); + } + } + if (matching.length === 0) { + return null; + } + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#functions.get(_fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .FunctionFragment */ .hc.from(key).format()); + if (result) { + return result; + } + return null; + } + /** + * Get the function name for %%key%%, which may be a function selector, + * function name or function signature that belongs to the ABI. + */ + getFunctionName(key) { + const fragment = this.#getFunction(key, null, false); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(fragment, "no matching function", "key", key); + return fragment.name; + } + /** + * Returns true if %%key%% (a function selector, function name or + * function signature) is present in the ABI. + * + * In the case of a function name, the name may be ambiguous, so + * accessing the [[FunctionFragment]] may require refinement. + */ + hasFunction(key) { + return !!this.#getFunction(key, null, false); + } + /** + * Get the [[FunctionFragment]] for %%key%%, which may be a function + * selector, function name or function signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple functions match by name. + * + * If the %%key%% and %%values%% do not refine to a single function in + * the ABI, this will throw. + */ + getFunction(key, values) { + return this.#getFunction(key, values || null, true); + } + /** + * Iterate over all functions, calling %%callback%%, sorted by their name. + */ + forEachFunction(callback) { + const names = Array.from(this.#functions.keys()); + names.sort((a, b) => a.localeCompare(b)); + for (let i = 0; i < names.length; i++) { + const name = names[i]; + callback((this.#functions.get(name)), i); + } + } + // Find an event definition by any means necessary (unless it is ambiguous) + #getEvent(key, values, forceUnique) { + // EventTopic + if ((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .isHexString */ .Lo)(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of this.#events.values()) { + if (eventTopic === fragment.topicHash) { + return fragment; + } + } + return null; + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#events) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + // Remove all matches that don't have a compatible length. + for (let i = matching.length - 1; i >= 0; i--) { + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!_typed_js__WEBPACK_IMPORTED_MODULE_5__/* .Typed */ .V.isTyped(values[j])) { + continue; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + return null; + } + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#events.get(_fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .EventFragment */ .Zp.from(key).format()); + if (result) { + return result; + } + return null; + } + /** + * Get the event name for %%key%%, which may be a topic hash, + * event name or event signature that belongs to the ABI. + */ + getEventName(key) { + const fragment = this.#getEvent(key, null, false); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(fragment, "no matching event", "key", key); + return fragment.name; + } + /** + * Returns true if %%key%% (an event topic hash, event name or + * event signature) is present in the ABI. + * + * In the case of an event name, the name may be ambiguous, so + * accessing the [[EventFragment]] may require refinement. + */ + hasEvent(key) { + return !!this.#getEvent(key, null, false); + } + /** + * Get the [[EventFragment]] for %%key%%, which may be a topic hash, + * event name or event signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple events match by name. + * + * If the %%key%% and %%values%% do not refine to a single event in + * the ABI, this will throw. + */ + getEvent(key, values) { + return this.#getEvent(key, values || null, true); + } + /** + * Iterate over all events, calling %%callback%%, sorted by their name. + */ + forEachEvent(callback) { + const names = Array.from(this.#events.keys()); + names.sort((a, b) => a.localeCompare(b)); + for (let i = 0; i < names.length; i++) { + const name = names[i]; + callback((this.#events.get(name)), i); + } + } + /** + * Get the [[ErrorFragment]] for %%key%%, which may be an error + * selector, error name or error signature that belongs to the ABI. + * + * If %%values%% is provided, it will use the Typed API to handle + * ambiguous cases where multiple errors match by name. + * + * If the %%key%% and %%values%% do not refine to a single error in + * the ABI, this will throw. + */ + getError(key, values) { + if ((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .isHexString */ .Lo)(key)) { + const selector = key.toLowerCase(); + if (BuiltinErrors[selector]) { + return _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from(BuiltinErrors[selector].signature); + } + for (const fragment of this.#errors.values()) { + if (selector === fragment.selector) { + return fragment; + } + } + return null; + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#errors) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from("error Error(string)"); + } + if (key === "Panic") { + return _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from("error Panic(uint256)"); + } + return null; + } + else if (matching.length > 1) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(false, `ambiguous error description (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + key = _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from(key).format(); + if (key === "Error(string)") { + return _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from("error Error(string)"); + } + if (key === "Panic(uint256)") { + return _fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorFragment */ .bp.from("error Panic(uint256)"); + } + const result = this.#errors.get(key); + if (result) { + return result; + } + return null; + } + /** + * Iterate over all errors, calling %%callback%%, sorted by their name. + */ + forEachError(callback) { + const names = Array.from(this.#errors.keys()); + names.sort((a, b) => a.localeCompare(b)); + for (let i = 0; i < names.length; i++) { + const name = names[i]; + callback((this.#errors.get(name)), i); + } + } + // Get the 4-byte selector used by Solidity to identify a function + /* +getSelector(fragment: ErrorFragment | FunctionFragment): string { + if (typeof(fragment) === "string") { + const matches: Array = [ ]; + + try { matches.push(this.getFunction(fragment)); } catch (error) { } + try { matches.push(this.getError(fragment)); } catch (_) { } + + if (matches.length === 0) { + logger.throwArgumentError("unknown fragment", "key", fragment); + } else if (matches.length > 1) { + logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); + } + + fragment = matches[0]; + } + + return dataSlice(id(fragment.format()), 0, 4); +} + */ + // Get the 32-byte topic hash used by Solidity to identify an event + /* + getEventTopic(fragment: EventFragment): string { + //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } + return id(fragment.format()); + } + */ + _decodeParams(params, data) { + return this.#abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this.#abiCoder.encode(params, values); + } + /** + * Encodes a ``tx.data`` object for deploying the Contract with + * the %%values%% as the constructor arguments. + */ + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + /** + * Decodes the result %%data%% (e.g. from an ``eth_call``) for the + * specified error (see [[getError]] for valid values for + * %%key%%). + * + * Most developers should prefer the [[parseCallResult]] method instead, + * which will automatically detect a ``CALL_EXCEPTION`` and throw the + * corresponding error. + */ + decodeErrorResult(fragment, data) { + if (typeof (fragment) === "string") { + const f = this.getError(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown error", "fragment", fragment); + fragment = f; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(data, 4)); + } + /** + * Encodes the transaction revert data for a call result that + * reverted from the the Contract with the sepcified %%error%% + * (see [[getError]] for valid values for %%fragment%%) with the %%values%%. + * + * This is generally not used by most developers, unless trying to mock + * a result from a Contract. + */ + encodeErrorResult(fragment, values) { + if (typeof (fragment) === "string") { + const f = this.getError(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown error", "fragment", fragment); + fragment = f; + } + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .concat */ .xW)([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); + } + /** + * Decodes the %%data%% from a transaction ``tx.data`` for + * the function specified (see [[getFunction]] for valid values + * for %%fragment%%). + * + * Most developers should prefer the [[parseTransaction]] method + * instead, which will automatically detect the fragment. + */ + decodeFunctionData(fragment, data) { + if (typeof (fragment) === "string") { + const f = this.getFunction(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown function", "fragment", fragment); + fragment = f; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(data, 4)); + } + /** + * Encodes the ``tx.data`` for a transaction that calls the function + * specified (see [[getFunction]] for valid values for %%fragment%%) with + * the %%values%%. + */ + encodeFunctionData(fragment, values) { + if (typeof (fragment) === "string") { + const f = this.getFunction(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown function", "fragment", fragment); + fragment = f; + } + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .concat */ .xW)([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); + } + /** + * Decodes the result %%data%% (e.g. from an ``eth_call``) for the + * specified function (see [[getFunction]] for valid values for + * %%key%%). + * + * Most developers should prefer the [[parseCallResult]] method instead, + * which will automatically detect a ``CALL_EXCEPTION`` and throw the + * corresponding error. + */ + decodeFunctionResult(fragment, data) { + if (typeof (fragment) === "string") { + const f = this.getFunction(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown function", "fragment", fragment); + fragment = f; + } + let message = "invalid length for result data"; + const bytes = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .getBytesCopy */ .Lm)(data); + if ((bytes.length % 32) === 0) { + try { + return this.#abiCoder.decode(fragment.outputs, bytes); + } + catch (error) { + message = "could not decode result data"; + } + } + // Call returned data with no error, but the data is junk + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assert */ .vA)(false, message, "BAD_DATA", { + value: (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(bytes), + info: { method: fragment.name, signature: fragment.format() } + }); + } + makeError(_data, tx) { + const data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .getBytes */ .q5)(_data, "data"); + const error = _abi_coder_js__WEBPACK_IMPORTED_MODULE_3__/* .AbiCoder */ .y.getBuiltinCallException("call", tx, data); + // Not a built-in error; try finding a custom error + const customPrefix = "execution reverted (unknown custom error)"; + if (error.message.startsWith(customPrefix)) { + const selector = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(data.slice(0, 4)); + const ef = this.getError(selector); + if (ef) { + try { + const args = this.#abiCoder.decode(ef.inputs, data.slice(4)); + error.revert = { + name: ef.name, signature: ef.format(), args + }; + error.reason = error.revert.signature; + error.message = `execution reverted: ${error.reason}`; + } + catch (e) { + error.message = `execution reverted (coult not decode custom error)`; + } + } + } + // Add the invocation, if available + const parsed = this.parseTransaction(tx); + if (parsed) { + error.invocation = { + method: parsed.name, + signature: parsed.signature, + args: parsed.args + }; + } + return error; + } + /** + * Encodes the result data (e.g. from an ``eth_call``) for the + * specified function (see [[getFunction]] for valid values + * for %%fragment%%) with %%values%%. + * + * This is generally not used by most developers, unless trying to mock + * a result from a Contract. + */ + encodeFunctionResult(fragment, values) { + if (typeof (fragment) === "string") { + const f = this.getFunction(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown function", "fragment", fragment); + fragment = f; + } + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(this.#abiCoder.encode(fragment.outputs, values || [])); + } + /* + spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { + const promises: Array> = [ ]; + const process = function(type: ParamType, value: any): any { + if (type.baseType === "array") { + return descend(type.child + } + if (type. === "address") { + } + }; + + const descend = function (inputs: Array, values: ReadonlyArray) { + if (inputs.length !== values.length) { throw new Error("length mismatch"); } + + }; + + const result: Array = [ ]; + values.forEach((value, index) => { + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + } + */ + // Create the filter for the event with search criteria (e.g. for eth_filterLog) + encodeFilterTopics(fragment, values) { + if (typeof (fragment) === "string") { + const f = this.getEvent(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assert */ .vA)(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length }); + const topics = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + // @TODO: Use the coders for this; to properly support tuples, etc. + const encodeTopic = (param, value) => { + if (param.type === "string") { + return (0,_hash_index_js__WEBPACK_IMPORTED_MODULE_6__.id)(value); + } + else if (param.type === "bytes") { + return (0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_7__/* .keccak256 */ .S)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(value)); + } + if (param.type === "bool" && typeof (value) === "boolean") { + value = (value ? "0x01" : "0x00"); + } + else if (param.type.match(/^u?int/)) { + value = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_8__/* .toBeHex */ .up)(value); // @TODO: Should this toTwos?? + } + else if (param.type.match(/^bytes/)) { + value = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .zeroPadBytes */ .X_)(value, 32); + } + else if (param.type === "address") { + // Check addresses are valid + this.#abiCoder.encode(["address"], [value]); + } + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .zeroPadValue */ .nx)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(value), 32); + }; + values.forEach((value, index) => { + const param = fragment.inputs[index]; + if (!param.indexed) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(value == null, "cannot filter non-indexed parameters; must be null", ("contract." + param.name), value); + return; + } + if (value == null) { + topics.push(null); + } + else if (param.baseType === "array" || param.baseType === "tuple") { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(false, "filtering with tuples or arrays not supported", ("contract." + param.name), value); + } + else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } + else { + topics.push(encodeTopic(param, value)); + } + }); + // Trim off trailing nulls + while (topics.length && topics[topics.length - 1] === null) { + topics.pop(); + } + return topics; + } + encodeEventLog(fragment, values) { + if (typeof (fragment) === "string") { + const f = this.getEvent(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values); + fragment.inputs.forEach((param, index) => { + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push((0,_hash_index_js__WEBPACK_IMPORTED_MODULE_6__.id)(value)); + } + else if (param.type === "bytes") { + topics.push((0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_7__/* .keccak256 */ .S)(value)); + } + else if (param.baseType === "tuple" || param.baseType === "array") { + // @TODO + throw new Error("not implemented"); + } + else { + topics.push(this.#abiCoder.encode([param.type], [value])); + } + } + else { + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this.#abiCoder.encode(dataTypes, dataValues), + topics: topics + }; + } + // Decode a filter for the event and the search criteria + decodeEventLog(fragment, data, topics) { + if (typeof (fragment) === "string") { + const f = this.getEvent(fragment); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + if (topics != null && !fragment.anonymous) { + const eventTopic = fragment.topicHash; + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .isHexString */ .Lo)(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]); + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + fragment.inputs.forEach((param, index) => { + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(_fragments_js__WEBPACK_IMPORTED_MODULE_1__/* .ParamType */ .aX.from({ type: "bytes32", name: param.name })); + dynamic.push(true); + } + else { + indexed.push(param); + dynamic.push(false); + } + } + else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .concat */ .xW)(topics)) : null; + const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); + //const result: (Array & { [ key: string ]: any }) = [ ]; + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + fragment.inputs.forEach((param, index) => { + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } + else if (dynamic[index]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } + else { + try { + value = resultIndexed[indexedIndex++]; + } + catch (error) { + value = error; + } + } + } + else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } + catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); + }); + return _coders_abstract_coder_js__WEBPACK_IMPORTED_MODULE_9__/* .Result */ .Q7.fromItems(values, keys); + } + /** + * Parses a transaction, finding the matching function and extracts + * the parameter values along with other useful function details. + * + * If the matching function cannot be found, return null. + */ + parseTransaction(tx) { + const data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .getBytes */ .q5)(tx.data, "tx.data"); + const value = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_8__/* .getBigInt */ .Ab)((tx.value != null) ? tx.value : 0, "tx.value"); + const fragment = this.getFunction((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, fragment.selector, args, value); + } + parseCallResult(data) { + throw new Error("@TODO"); + } + /** + * Parses a receipt log, finding the matching event and extracts + * the parameter values along with other useful event details. + * + * If the matching event cannot be found, returns null. + */ + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + // @TODO: If anonymous, and the only method, and the input count matches, should we parse? + // Probably not, because just because it is the only event in the ABI does + // not mean we have the full ABI; maybe just a fragment? + return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); + } + /** + * Parses a revert data, finding the matching error and extracts + * the parameter values along with other useful error details. + * + * If the matching error cannot be found, returns null. + */ + parseError(data) { + const hexData = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .hexlify */ .c$)(data); + const fragment = this.getError((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(hexData, 0, 4)); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .dataSlice */ .ZG)(hexData, 4)); + return new ErrorDescription(fragment, fragment.selector, args); + } + /** + * Creates a new [[Interface]] from the ABI %%value%%. + * + * The %%value%% may be provided as an existing [[Interface]] object, + * a JSON-encoded ABI or any Human-Readable ABI format. + */ + static from(value) { + // Already an Interface, which is immutable + if (value instanceof Interface) { + return value; + } + // JSON + if (typeof (value) === "string") { + return new Interface(JSON.parse(value)); + } + // Maybe an interface from an older version, or from a symlinked copy + if (typeof (value.format) === "function") { + return new Interface(value.format("json")); + } + // Array of fragments + return new Interface(value); + } +} +//# sourceMappingURL=interface.js.map + +/***/ }), + +/***/ 19353: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ V: () => (/* binding */ Typed) +/* harmony export */ }); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(88081); +/** + * A Typed object allows a value to have its type explicitly + * specified. + * + * For example, in Solidity, the value ``45`` could represent a + * ``uint8`` or a ``uint256``. The value ``0x1234`` could represent + * a ``bytes2`` or ``bytes``. + * + * Since JavaScript has no meaningful way to explicitly inform any + * APIs which what the type is, this allows transparent interoperation + * with Soldity. + * + * @_subsection: api/abi:Typed Values + */ + +const _gaurd = {}; +function n(value, width) { + let signed = false; + if (width < 0) { + signed = true; + width *= -1; + } + // @TODO: Check range is valid for value + return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width }); +} +function b(value, size) { + // @TODO: Check range is valid for value + return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size }); +} +const _typedSymbol = Symbol.for("_ethers_typed"); +/** + * The **Typed** class to wrap values providing explicit type information. + */ +class Typed { + /** + * The type, as a Solidity-compatible type. + */ + type; + /** + * The actual value. + */ + value; + #options; + /** + * @_ignore: + */ + _typedSymbol; + /** + * @_ignore: + */ + constructor(gaurd, type, value, options) { + if (options == null) { + options = null; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertPrivate */ .gk)(_gaurd, gaurd, "Typed"); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .defineProperties */ .n)(this, { _typedSymbol, type, value }); + this.#options = options; + // Check the value is valid + this.format(); + } + /** + * Format the type as a Human-Readable type. + */ + format() { + if (this.type === "array") { + throw new Error(""); + } + else if (this.type === "dynamicArray") { + throw new Error(""); + } + else if (this.type === "tuple") { + return `tuple(${this.value.map((v) => v.format()).join(",")})`; + } + return this.type; + } + /** + * The default value returned by this type. + */ + defaultValue() { + return 0; + } + /** + * The minimum value for numeric types. + */ + minValue() { + return 0; + } + /** + * The maximum value for numeric types. + */ + maxValue() { + return 0; + } + /** + * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]]. + */ + isBigInt() { + return !!(this.type.match(/^u?int[0-9]+$/)); + } + /** + * Returns ``true`` and provides a type guard is this is a [[TypedData]]. + */ + isData() { + return this.type.startsWith("bytes"); + } + /** + * Returns ``true`` and provides a type guard is this is a [[TypedString]]. + */ + isString() { + return (this.type === "string"); + } + /** + * Returns the tuple name, if this is a tuple. Throws otherwise. + */ + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); + } + return this.#options; + } + // Returns the length of this type as an array + // - `null` indicates the length is unforced, it could be dynamic + // - `-1` indicates the length is dynamic + // - any other value indicates it is a static array and is its length + /** + * Returns the length of the array type or ``-1`` if it is dynamic. + * + * Throws if the type is not an array. + */ + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); + } + if (this.#options === true) { + return -1; + } + if (this.#options === false) { + return (this.value).length; + } + return null; + } + /** + * Returns a new **Typed** of %%type%% with the %%value%%. + */ + static from(type, value) { + return new Typed(_gaurd, type, value); + } + /** + * Return a new ``uint8`` type for %%v%%. + */ + static uint8(v) { return n(v, 8); } + /** + * Return a new ``uint16`` type for %%v%%. + */ + static uint16(v) { return n(v, 16); } + /** + * Return a new ``uint24`` type for %%v%%. + */ + static uint24(v) { return n(v, 24); } + /** + * Return a new ``uint32`` type for %%v%%. + */ + static uint32(v) { return n(v, 32); } + /** + * Return a new ``uint40`` type for %%v%%. + */ + static uint40(v) { return n(v, 40); } + /** + * Return a new ``uint48`` type for %%v%%. + */ + static uint48(v) { return n(v, 48); } + /** + * Return a new ``uint56`` type for %%v%%. + */ + static uint56(v) { return n(v, 56); } + /** + * Return a new ``uint64`` type for %%v%%. + */ + static uint64(v) { return n(v, 64); } + /** + * Return a new ``uint72`` type for %%v%%. + */ + static uint72(v) { return n(v, 72); } + /** + * Return a new ``uint80`` type for %%v%%. + */ + static uint80(v) { return n(v, 80); } + /** + * Return a new ``uint88`` type for %%v%%. + */ + static uint88(v) { return n(v, 88); } + /** + * Return a new ``uint96`` type for %%v%%. + */ + static uint96(v) { return n(v, 96); } + /** + * Return a new ``uint104`` type for %%v%%. + */ + static uint104(v) { return n(v, 104); } + /** + * Return a new ``uint112`` type for %%v%%. + */ + static uint112(v) { return n(v, 112); } + /** + * Return a new ``uint120`` type for %%v%%. + */ + static uint120(v) { return n(v, 120); } + /** + * Return a new ``uint128`` type for %%v%%. + */ + static uint128(v) { return n(v, 128); } + /** + * Return a new ``uint136`` type for %%v%%. + */ + static uint136(v) { return n(v, 136); } + /** + * Return a new ``uint144`` type for %%v%%. + */ + static uint144(v) { return n(v, 144); } + /** + * Return a new ``uint152`` type for %%v%%. + */ + static uint152(v) { return n(v, 152); } + /** + * Return a new ``uint160`` type for %%v%%. + */ + static uint160(v) { return n(v, 160); } + /** + * Return a new ``uint168`` type for %%v%%. + */ + static uint168(v) { return n(v, 168); } + /** + * Return a new ``uint176`` type for %%v%%. + */ + static uint176(v) { return n(v, 176); } + /** + * Return a new ``uint184`` type for %%v%%. + */ + static uint184(v) { return n(v, 184); } + /** + * Return a new ``uint192`` type for %%v%%. + */ + static uint192(v) { return n(v, 192); } + /** + * Return a new ``uint200`` type for %%v%%. + */ + static uint200(v) { return n(v, 200); } + /** + * Return a new ``uint208`` type for %%v%%. + */ + static uint208(v) { return n(v, 208); } + /** + * Return a new ``uint216`` type for %%v%%. + */ + static uint216(v) { return n(v, 216); } + /** + * Return a new ``uint224`` type for %%v%%. + */ + static uint224(v) { return n(v, 224); } + /** + * Return a new ``uint232`` type for %%v%%. + */ + static uint232(v) { return n(v, 232); } + /** + * Return a new ``uint240`` type for %%v%%. + */ + static uint240(v) { return n(v, 240); } + /** + * Return a new ``uint248`` type for %%v%%. + */ + static uint248(v) { return n(v, 248); } + /** + * Return a new ``uint256`` type for %%v%%. + */ + static uint256(v) { return n(v, 256); } + /** + * Return a new ``uint256`` type for %%v%%. + */ + static uint(v) { return n(v, 256); } + /** + * Return a new ``int8`` type for %%v%%. + */ + static int8(v) { return n(v, -8); } + /** + * Return a new ``int16`` type for %%v%%. + */ + static int16(v) { return n(v, -16); } + /** + * Return a new ``int24`` type for %%v%%. + */ + static int24(v) { return n(v, -24); } + /** + * Return a new ``int32`` type for %%v%%. + */ + static int32(v) { return n(v, -32); } + /** + * Return a new ``int40`` type for %%v%%. + */ + static int40(v) { return n(v, -40); } + /** + * Return a new ``int48`` type for %%v%%. + */ + static int48(v) { return n(v, -48); } + /** + * Return a new ``int56`` type for %%v%%. + */ + static int56(v) { return n(v, -56); } + /** + * Return a new ``int64`` type for %%v%%. + */ + static int64(v) { return n(v, -64); } + /** + * Return a new ``int72`` type for %%v%%. + */ + static int72(v) { return n(v, -72); } + /** + * Return a new ``int80`` type for %%v%%. + */ + static int80(v) { return n(v, -80); } + /** + * Return a new ``int88`` type for %%v%%. + */ + static int88(v) { return n(v, -88); } + /** + * Return a new ``int96`` type for %%v%%. + */ + static int96(v) { return n(v, -96); } + /** + * Return a new ``int104`` type for %%v%%. + */ + static int104(v) { return n(v, -104); } + /** + * Return a new ``int112`` type for %%v%%. + */ + static int112(v) { return n(v, -112); } + /** + * Return a new ``int120`` type for %%v%%. + */ + static int120(v) { return n(v, -120); } + /** + * Return a new ``int128`` type for %%v%%. + */ + static int128(v) { return n(v, -128); } + /** + * Return a new ``int136`` type for %%v%%. + */ + static int136(v) { return n(v, -136); } + /** + * Return a new ``int144`` type for %%v%%. + */ + static int144(v) { return n(v, -144); } + /** + * Return a new ``int52`` type for %%v%%. + */ + static int152(v) { return n(v, -152); } + /** + * Return a new ``int160`` type for %%v%%. + */ + static int160(v) { return n(v, -160); } + /** + * Return a new ``int168`` type for %%v%%. + */ + static int168(v) { return n(v, -168); } + /** + * Return a new ``int176`` type for %%v%%. + */ + static int176(v) { return n(v, -176); } + /** + * Return a new ``int184`` type for %%v%%. + */ + static int184(v) { return n(v, -184); } + /** + * Return a new ``int92`` type for %%v%%. + */ + static int192(v) { return n(v, -192); } + /** + * Return a new ``int200`` type for %%v%%. + */ + static int200(v) { return n(v, -200); } + /** + * Return a new ``int208`` type for %%v%%. + */ + static int208(v) { return n(v, -208); } + /** + * Return a new ``int216`` type for %%v%%. + */ + static int216(v) { return n(v, -216); } + /** + * Return a new ``int224`` type for %%v%%. + */ + static int224(v) { return n(v, -224); } + /** + * Return a new ``int232`` type for %%v%%. + */ + static int232(v) { return n(v, -232); } + /** + * Return a new ``int240`` type for %%v%%. + */ + static int240(v) { return n(v, -240); } + /** + * Return a new ``int248`` type for %%v%%. + */ + static int248(v) { return n(v, -248); } + /** + * Return a new ``int256`` type for %%v%%. + */ + static int256(v) { return n(v, -256); } + /** + * Return a new ``int256`` type for %%v%%. + */ + static int(v) { return n(v, -256); } + /** + * Return a new ``bytes1`` type for %%v%%. + */ + static bytes1(v) { return b(v, 1); } + /** + * Return a new ``bytes2`` type for %%v%%. + */ + static bytes2(v) { return b(v, 2); } + /** + * Return a new ``bytes3`` type for %%v%%. + */ + static bytes3(v) { return b(v, 3); } + /** + * Return a new ``bytes4`` type for %%v%%. + */ + static bytes4(v) { return b(v, 4); } + /** + * Return a new ``bytes5`` type for %%v%%. + */ + static bytes5(v) { return b(v, 5); } + /** + * Return a new ``bytes6`` type for %%v%%. + */ + static bytes6(v) { return b(v, 6); } + /** + * Return a new ``bytes7`` type for %%v%%. + */ + static bytes7(v) { return b(v, 7); } + /** + * Return a new ``bytes8`` type for %%v%%. + */ + static bytes8(v) { return b(v, 8); } + /** + * Return a new ``bytes9`` type for %%v%%. + */ + static bytes9(v) { return b(v, 9); } + /** + * Return a new ``bytes10`` type for %%v%%. + */ + static bytes10(v) { return b(v, 10); } + /** + * Return a new ``bytes11`` type for %%v%%. + */ + static bytes11(v) { return b(v, 11); } + /** + * Return a new ``bytes12`` type for %%v%%. + */ + static bytes12(v) { return b(v, 12); } + /** + * Return a new ``bytes13`` type for %%v%%. + */ + static bytes13(v) { return b(v, 13); } + /** + * Return a new ``bytes14`` type for %%v%%. + */ + static bytes14(v) { return b(v, 14); } + /** + * Return a new ``bytes15`` type for %%v%%. + */ + static bytes15(v) { return b(v, 15); } + /** + * Return a new ``bytes16`` type for %%v%%. + */ + static bytes16(v) { return b(v, 16); } + /** + * Return a new ``bytes17`` type for %%v%%. + */ + static bytes17(v) { return b(v, 17); } + /** + * Return a new ``bytes18`` type for %%v%%. + */ + static bytes18(v) { return b(v, 18); } + /** + * Return a new ``bytes19`` type for %%v%%. + */ + static bytes19(v) { return b(v, 19); } + /** + * Return a new ``bytes20`` type for %%v%%. + */ + static bytes20(v) { return b(v, 20); } + /** + * Return a new ``bytes21`` type for %%v%%. + */ + static bytes21(v) { return b(v, 21); } + /** + * Return a new ``bytes22`` type for %%v%%. + */ + static bytes22(v) { return b(v, 22); } + /** + * Return a new ``bytes23`` type for %%v%%. + */ + static bytes23(v) { return b(v, 23); } + /** + * Return a new ``bytes24`` type for %%v%%. + */ + static bytes24(v) { return b(v, 24); } + /** + * Return a new ``bytes25`` type for %%v%%. + */ + static bytes25(v) { return b(v, 25); } + /** + * Return a new ``bytes26`` type for %%v%%. + */ + static bytes26(v) { return b(v, 26); } + /** + * Return a new ``bytes27`` type for %%v%%. + */ + static bytes27(v) { return b(v, 27); } + /** + * Return a new ``bytes28`` type for %%v%%. + */ + static bytes28(v) { return b(v, 28); } + /** + * Return a new ``bytes29`` type for %%v%%. + */ + static bytes29(v) { return b(v, 29); } + /** + * Return a new ``bytes30`` type for %%v%%. + */ + static bytes30(v) { return b(v, 30); } + /** + * Return a new ``bytes31`` type for %%v%%. + */ + static bytes31(v) { return b(v, 31); } + /** + * Return a new ``bytes32`` type for %%v%%. + */ + static bytes32(v) { return b(v, 32); } + /** + * Return a new ``address`` type for %%v%%. + */ + static address(v) { return new Typed(_gaurd, "address", v); } + /** + * Return a new ``bool`` type for %%v%%. + */ + static bool(v) { return new Typed(_gaurd, "bool", !!v); } + /** + * Return a new ``bytes`` type for %%v%%. + */ + static bytes(v) { return new Typed(_gaurd, "bytes", v); } + /** + * Return a new ``string`` type for %%v%%. + */ + static string(v) { return new Typed(_gaurd, "string", v); } + /** + * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length. + */ + static array(v, dynamic) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "array", v, dynamic); + } + /** + * Return a new ``tuple`` type for %%v%%, with the optional %%name%%. + */ + static tuple(v, name) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "tuple", v, name); + } + /** + * Return a new ``uint8`` type for %%v%%. + */ + static overrides(v) { + return new Typed(_gaurd, "overrides", Object.assign({}, v)); + } + /** + * Returns true only if %%value%% is a [[Typed]] instance. + */ + static isTyped(value) { + return (value + && typeof (value) === "object" + && "_typedSymbol" in value + && value._typedSymbol === _typedSymbol); + } + /** + * If the value is a [[Typed]] instance, validates the underlying value + * and returns it, otherwise returns value directly. + * + * This is useful for functions that with to accept either a [[Typed]] + * object or values. + */ + static dereference(value, type) { + if (Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); + } + return value.value; + } + return value; + } +} +//# sourceMappingURL=typed.js.map + +/***/ }), + +/***/ 30031: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ b: () => (/* binding */ getAddress) +/* harmony export */ }); +/* unused harmony export getIcapAddress */ +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15539); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36212); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(57339); + + +const BN_0 = BigInt(0); +const BN_36 = BigInt(36); +function getChecksumAddress(address) { + // if (!isHexString(address, 20)) { + // logger.throwArgumentError("invalid address", "address", address); + // } + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); + } + const hashed = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .getBytes */ .q5)((0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_1__/* .keccak256 */ .S)(expanded)); + for (let i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return "0x" + chars.join(""); +} +// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number +// Create lookup table +const ibanLookup = {}; +for (let i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); +} +for (let i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +// How many decimal digits can we process? (for 64-bit float, this is 15) +// i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER)); +const safeDigits = 15; +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join(""); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + let checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = "0" + checksum; + } + return checksum; +} +; +const Base36 = (function () { + ; + const result = {}; + for (let i = 0; i < 36; i++) { + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); + } + return result; +})(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0; + for (let i = 0; i < value.length; i++) { + result = result * BN_36 + Base36[value[i]]; + } + return result; +} +/** + * Returns a normalized and checksumed address for %%address%%. + * This accepts non-checksum addresses, checksum addresses and + * [[getIcapAddress]] formats. + * + * The checksum in Ethereum uses the capitalization (upper-case + * vs lower-case) of the characters within an address to encode + * its checksum, which offers, on average, a checksum of 15-bits. + * + * If %%address%% contains both upper-case and lower-case, it is + * assumed to already be a checksum address and its checksum is + * validated, and if the address fails its expected checksum an + * error is thrown. + * + * If you wish the checksum of %%address%% to be ignore, it should + * be converted to lower-case (i.e. ``.toLowercase()``) before + * being passed in. This should be a very rare situation though, + * that you wish to bypass the safegaurds in place to protect + * against an address that has been incorrectly copied from another + * source. + * + * @example: + * // Adds the checksum (via upper-casing specific letters) + * getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72") + * //_result: + * + * // Converts ICAP address and adds checksum + * getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); + * //_result: + * + * // Throws an error if an address contains mixed case, + * // but the checksum fails + * getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") + * //_error: + */ +function getAddress(address) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(typeof (address) === "string", "invalid address", "address", address); + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (!address.startsWith("0x")) { + address = "0x" + address; + } + const result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address); + return result; + } + // Maybe ICAP? (we only support direct mode) + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address); + let result = fromBase36(address.substring(4)).toString(16); + while (result.length < 40) { + result = "0" + result; + } + return getChecksumAddress("0x" + result); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .assertArgument */ .MR)(false, "invalid address", "address", address); +} +/** + * The [ICAP Address format](link-icap) format is an early checksum + * format which attempts to be compatible with the banking + * industry [IBAN format](link-wiki-iban) for bank accounts. + * + * It is no longer common or a recommended format. + * + * @example: + * getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); + * //_result: + * + * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); + * //_result: + * + * // Throws an error if the ICAP checksum is wrong + * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"); + * //_error: + */ +function getIcapAddress(address) { + //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = "0" + base36; + } + return "XE" + ibanChecksum("XE00" + base36) + base36; +} +//# sourceMappingURL=address.js.map + +/***/ }), + +/***/ 41442: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $C: () => (/* binding */ isAddressable), +/* harmony export */ tG: () => (/* binding */ resolveAddress) +/* harmony export */ }); +/* unused harmony export isAddress */ +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/* harmony import */ var _address_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30031); + + +/** + * Returns true if %%value%% is an object which implements the + * [[Addressable]] interface. + * + * @example: + * // Wallets and AbstractSigner sub-classes + * isAddressable(Wallet.createRandom()) + * //_result: + * + * // Contracts + * contract = new Contract("dai.tokens.ethers.eth", [ ], provider) + * isAddressable(contract) + * //_result: + */ +function isAddressable(value) { + return (value && typeof (value.getAddress) === "function"); +} +/** + * Returns true if %%value%% is a valid address. + * + * @example: + * // Valid address + * isAddress("0x8ba1f109551bD432803012645Ac136ddd64DBA72") + * //_result: + * + * // Valid ICAP address + * isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36") + * //_result: + * + * // Invalid checksum + * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBa72") + * //_result: + * + * // Invalid ICAP checksum + * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") + * //_result: + * + * // Not an address (an ENS name requires a provided and an + * // asynchronous API to access) + * isAddress("ricmoo.eth") + * //_result: + */ +function isAddress(value) { + try { + getAddress(value); + return true; + } + catch (error) { } + return false; +} +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(typeof (target) !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, "invalid AddressLike value; did not resolve to a value address", "target", target); + } + return (0,_address_js__WEBPACK_IMPORTED_MODULE_1__/* .getAddress */ .b)(result); +} +/** + * Resolves to an address for the %%target%%, which may be any + * supported address type, an [[Addressable]] or a Promise which + * resolves to an address. + * + * If an ENS name is provided, but that name has not been correctly + * configured a [[UnconfiguredNameError]] is thrown. + * + * @example: + * addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F" + * + * // Addresses are return synchronously + * resolveAddress(addr, provider) + * //_result: + * + * // Address promises are resolved asynchronously + * resolveAddress(Promise.resolve(addr)) + * //_result: + * + * // ENS names are resolved asynchronously + * resolveAddress("dai.tokens.ethers.eth", provider) + * //_result: + * + * // Addressable objects are resolved asynchronously + * contract = new Contract(addr, [ ]) + * resolveAddress(contract, provider) + * //_result: + * + * // Unconfigured ENS names reject + * resolveAddress("nothing-here.ricmoo.eth", provider) + * //_error: + * + * // ENS names require a NameResolver object passed in + * // (notice the provider was omitted) + * resolveAddress("nothing-here.ricmoo.eth") + * //_error: + */ +function resolveAddress(target, resolver) { + if (typeof (target) === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return (0,_address_js__WEBPACK_IMPORTED_MODULE_1__/* .getAddress */ .b)(target); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" }); + return checkAddress(target, resolver.resolveName(target)); + } + else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } + else if (target && typeof (target.then) === "function") { + return checkAddress(target, target); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, "unsupported addressable value", "target", target); +} +//# sourceMappingURL=checks.js.map + +/***/ }), + +/***/ 98982: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ ZeroAddress) +/* harmony export */ }); +/** + * A constant for the zero address. + * + * (**i.e.** ``"0x0000000000000000000000000000000000000000"``) + */ +const ZeroAddress = "0x0000000000000000000000000000000000000000"; +//# sourceMappingURL=addresses.js.map + +/***/ }), + +/***/ 24391: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + NZ: () => (/* binding */ Contract) +}); + +// UNUSED EXPORTS: BaseContract, copyOverrides, resolveArgs + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/typed.js +var typed = __webpack_require__(19353); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/abi/interface.js +var abi_interface = __webpack_require__(73622); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/checks.js +var checks = __webpack_require__(41442); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/providers/provider.js +var providers_provider = __webpack_require__(43948); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var data = __webpack_require__(36212); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/events.js +var events = __webpack_require__(99381); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/contract/wrappers.js +// import from provider.ts instead of index.ts to prevent circular dep +// from EtherscanProvider + + +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +class EventLog extends providers_provider/* Log */.tG { + /** + * The Contract Interface. + */ + interface; + /** + * The matching event. + */ + fragment; + /** + * The parsed arguments passed to the event by ``emit``. + */ + args; + /** + * @_ignore: + */ + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + (0,properties/* defineProperties */.n)(this, { args, fragment, interface: iface }); + } + /** + * The name of the event. + */ + get eventName() { return this.fragment.name; } + /** + * The signature of the event. + */ + get eventSignature() { return this.fragment.format(); } +} +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +class UndecodedEventLog extends providers_provider/* Log */.tG { + /** + * The error encounted when trying to decode the log. + */ + error; + /** + * @_ignore: + */ + constructor(log, error) { + super(log, log.provider); + (0,properties/* defineProperties */.n)(this, { error }); + } +} +/** + * A **ContractTransactionReceipt** includes the parsed logs from a + * [[TransactionReceipt]]. + */ +class ContractTransactionReceipt extends providers_provider/* TransactionReceipt */.z5 { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; + if (fragment) { + try { + return new EventLog(log, this.#iface, fragment); + } + catch (error) { + return new UndecodedEventLog(log, error); + } + } + return log; + }); + } +} +/** + * A **ContractTransactionResponse** will return a + * [[ContractTransactionReceipt]] when waited on. + */ +class ContractTransactionResponse extends providers_provider/* TransactionResponse */.uI { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(confirms, timeout) { + const receipt = await super.wait(confirms, timeout); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#iface, this.provider, receipt); + } +} +/** + * A **ContractUnknownEventPayload** is included as the last parameter to + * Contract Events when the event does not match any events in the ABI. + */ +class ContractUnknownEventPayload extends events/* EventPayload */.z { + /** + * The log with no matching events. + */ + log; + /** + * @_event: + */ + constructor(contract, listener, filter, log) { + super(contract, listener, filter); + (0,properties/* defineProperties */.n)(this, { log }); + } + /** + * Resolves to the block the event occured in. + */ + async getBlock() { + return await this.log.getBlock(); + } + /** + * Resolves to the transaction the event occured in. + */ + async getTransaction() { + return await this.log.getTransaction(); + } + /** + * Resolves to the transaction receipt the event occured in. + */ + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} +/** + * A **ContractEventPayload** is included as the last parameter to + * Contract Events when the event is known. + */ +class ContractEventPayload extends ContractUnknownEventPayload { + /** + * @_ignore: + */ + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); + const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); + (0,properties/* defineProperties */.n)(this, { args, fragment }); + } + /** + * The event name. + */ + get eventName() { + return this.fragment.name; + } + /** + * The event signature. + */ + get eventSignature() { + return this.fragment.format(); + } +} +//# sourceMappingURL=wrappers.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/contract/contract.js + + +// import from provider.ts instead of index.ts to prevent circular dep +// from EtherscanProvider + + + +const BN_0 = BigInt(0); +function canCall(value) { + return (value && typeof (value.call) === "function"); +} +function canEstimate(value) { + return (value && typeof (value.estimateGas) === "function"); +} +function canResolve(value) { + return (value && typeof (value.resolveName) === "function"); +} +function canSend(value) { + return (value && typeof (value.sendTransaction) === "function"); +} +function getResolver(value) { + if (value != null) { + if (canResolve(value)) { + return value; + } + if (value.provider) { + return value.provider; + } + } + return undefined; +} +class PreparedTopicFilter { + #filter; + fragment; + constructor(contract, fragment, args) { + (0,properties/* defineProperties */.n)(this, { fragment }); + if (fragment.inputs.length < args.length) { + throw new Error("too many arguments"); + } + // Recursively descend into args and resolve any addresses + const runner = getRunner(contract.runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + this.#filter = (async function () { + const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => { + const arg = args[index]; + if (arg == null) { + return null; + } + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + if (Array.isArray(value)) { + return Promise.all(value.map((v) => (0,checks/* resolveAddress */.tG)(v, resolver))); + } + return (0,checks/* resolveAddress */.tG)(value, resolver); + } + return value; + }); + })); + return contract.interface.encodeFilterTopics(fragment, resolvedArgs); + })(); + } + getTopicFilter() { + return this.#filter; + } +} +// A = Arguments passed in as a tuple +// R = The result type of the call (i.e. if only one return type, +// the qualified type, otherwise Result) +// D = The type the default call will return (i.e. R for view/pure, +// TransactionResponse otherwise) +//export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> { +function getRunner(value, feature) { + if (value == null) { + return null; + } + if (typeof (value[feature]) === "function") { + return value; + } + if (value.provider && typeof (value.provider[feature]) === "function") { + return value.provider; + } + return null; +} +function getProvider(value) { + if (value == null) { + return null; + } + return value.provider || null; +} +/** + * @_ignore: + */ +async function copyOverrides(arg, allowed) { + // Make sure the overrides passed in are a valid overrides object + const _overrides = typed/* Typed */.V.dereference(arg, "overrides"); + (0,errors/* assertArgument */.MR)(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg); + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = (0,providers_provider/* copyRequest */.VS)(_overrides); + (0,errors/* assertArgument */.MR)(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); + (0,errors/* assertArgument */.MR)(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); + // Resolve any from + if (overrides.from) { + overrides.from = overrides.from; + } + return overrides; +} +/** + * @_ignore: + */ +async function resolveArgs(_runner, inputs, args) { + // Recursively descend into args and resolve any addresses + const runner = getRunner(_runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + return await Promise.all(inputs.map((param, index) => { + return param.walkAsync(args[index], (type, value) => { + value = typed/* Typed */.V.dereference(value, type); + if (type === "address") { + return (0,checks/* resolveAddress */.tG)(value, resolver); + } + return value; + }); + })); +} +function buildWrappedFallback(contract) { + const populateTransaction = async function (overrides) { + // If an overrides was passed in, copy it and normalize the values + const tx = (await copyOverrides(overrides, ["data"])); + tx.to = await contract.getAddress(); + if (tx.from) { + tx.from = await (0,checks/* resolveAddress */.tG)(tx.from, getResolver(contract.runner)); + } + const iface = contract.interface; + const noValue = ((0,maths/* getBigInt */.Ab)((tx.value || BN_0), "overrides.value") === BN_0); + const noData = ((tx.data || "0x") === "0x"); + if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { + (0,errors/* assertArgument */.MR)(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); + } + (0,errors/* assertArgument */.MR)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + // Only allow payable contracts to set non-zero value + const payable = iface.receive || (iface.fallback && iface.fallback.payable); + (0,errors/* assertArgument */.MR)(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); + // Only allow fallback contracts to set non-empty data + (0,errors/* assertArgument */.MR)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + return tx; + }; + const staticCall = async function (overrides) { + const runner = getRunner(contract.runner, "call"); + (0,errors/* assert */.vA)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(overrides); + try { + return await runner.call(tx); + } + catch (error) { + if ((0,errors/* isCallException */.E)(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + }; + const send = async function (overrides) { + const runner = contract.runner; + (0,errors/* assert */.vA)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(overrides)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (overrides) { + const runner = getRunner(contract.runner, "estimateGas"); + (0,errors/* assert */.vA)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(overrides)); + }; + const method = async (overrides) => { + return await send(overrides); + }; + (0,properties/* defineProperties */.n)(method, { + _contract: contract, + estimateGas, + populateTransaction, + send, staticCall + }); + return method; +} +function buildWrappedMethod(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getFunction(key, args); + (0,errors/* assert */.vA)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const populateTransaction = async function (...args) { + const fragment = getFragment(...args); + // If an overrides was passed in, copy it and normalize the values + let overrides = {}; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + if (overrides.from) { + overrides.from = await (0,checks/* resolveAddress */.tG)(overrides.from, getResolver(contract.runner)); + } + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await (0,properties/* resolveProperties */.k)({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + }; + const staticCall = async function (...args) { + const result = await staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + }; + const send = async function (...args) { + const runner = contract.runner; + (0,errors/* assert */.vA)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(...args)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (...args) { + const runner = getRunner(contract.runner, "estimateGas"); + (0,errors/* assert */.vA)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(...args)); + }; + const staticCallResult = async function (...args) { + const runner = getRunner(contract.runner, "call"); + (0,errors/* assert */.vA)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if ((0,errors/* isCallException */.E)(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + const fragment = getFragment(...args); + return contract.interface.decodeFunctionResult(fragment, result); + }; + const method = async (...args) => { + const fragment = getFragment(...args); + if (fragment.constant) { + return await staticCall(...args); + } + return await send(...args); + }; + (0,properties/* defineProperties */.n)(method, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key, + getFragment, + estimateGas, + populateTransaction, + send, staticCall, staticCallResult, + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getFunction(key); + (0,errors/* assert */.vA)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +function buildWrappedEvent(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getEvent(key, args); + (0,errors/* assert */.vA)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const method = function (...args) { + return new PreparedTopicFilter(contract, getFragment(...args), args); + }; + (0,properties/* defineProperties */.n)(method, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key, + getFragment + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getEvent(key); + (0,errors/* assert */.vA)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +// The combination of TypeScrype, Private Fields and Proxies makes +// the world go boom; so we hide variables with some trickery keeping +// a symbol attached to each BaseContract which its sub-class (even +// via a Proxy) can reach and use to look up its internal values. +const internal = Symbol.for("_ethersInternal_contract"); +const internalValues = new WeakMap(); +function setInternal(contract, values) { + internalValues.set(contract[internal], values); +} +function getInternal(contract) { + return internalValues.get(contract[internal]); +} +function isDeferred(value) { + return (value && typeof (value) === "object" && ("getTopicFilter" in value) && + (typeof (value.getTopicFilter) === "function") && value.fragment); +} +async function getSubInfo(contract, event) { + let topics; + let fragment = null; + // Convert named events to topicHash and get the fragment for + // events which need deconstructing. + if (Array.isArray(event)) { + const topicHashify = function (name) { + if ((0,data/* isHexString */.Lo)(name, 32)) { + return name; + } + const fragment = contract.interface.getEvent(name); + (0,errors/* assertArgument */.MR)(fragment, "unknown fragment", "name", name); + return fragment.topicHash; + }; + // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]` + topics = event.map((e) => { + if (e == null) { + return null; + } + if (Array.isArray(e)) { + return e.map(topicHashify); + } + return topicHashify(e); + }); + } + else if (event === "*") { + topics = [null]; + } + else if (typeof (event) === "string") { + if ((0,data/* isHexString */.Lo)(event, 32)) { + // Topic Hash + topics = [event]; + } + else { + // Name or Signature; e.g. `"Transfer", `"Transfer(address)"` + fragment = contract.interface.getEvent(event); + (0,errors/* assertArgument */.MR)(fragment, "unknown fragment", "event", event); + topics = [fragment.topicHash]; + } + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [fragment.topicHash]; + } + else { + (0,errors/* assertArgument */.MR)(false, "unknown event name", "event", event); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values()); + if (items.length === 1) { + return items[0]; + } + items.sort(); + return items; + } + return t.toLowerCase(); + }); + const tag = topics.map((t) => { + if (t == null) { + return "null"; + } + if (Array.isArray(t)) { + return t.join("|"); + } + return t; + }).join("&"); + return { fragment, tag, topics }; +} +async function hasSub(contract, event) { + const { subs } = getInternal(contract); + return subs.get((await getSubInfo(contract, event)).tag) || null; +} +async function getSub(contract, operation, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + (0,errors/* assert */.vA)(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation }); + const { fragment, tag, topics } = await getSubInfo(contract, event); + const { addr, subs } = getInternal(contract); + let sub = subs.get(tag); + if (!sub) { + const address = (addr ? addr : contract); + const filter = { address, topics }; + const listener = (log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = contract.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + // If fragment is null, we do not deconstruct the args to emit + if (foundFragment) { + const _foundFragment = foundFragment; + const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; + emit(contract, event, args, (listener) => { + return new ContractEventPayload(contract, listener, event, _foundFragment, log); + }); + } + else { + emit(contract, event, [], (listener) => { + return new ContractUnknownEventPayload(contract, listener, event, log); + }); + } + }; + let starting = []; + const start = () => { + if (starting.length) { + return; + } + starting.push(provider.on(filter, listener)); + }; + const stop = async () => { + if (starting.length == 0) { + return; + } + let started = starting; + starting = []; + await Promise.all(started); + provider.off(filter, listener); + }; + sub = { tag, listeners: [], start, stop }; + subs.set(tag, sub); + } + return sub; +} +// We use this to ensure one emit resolves before firing the next to +// ensure correct ordering (note this cannot throw and just adds the +// notice to the event queu using setTimeout). +let lastEmit = Promise.resolve(); +async function _emit(contract, event, args, payloadFunc) { + await lastEmit; + const sub = await hasSub(contract, event); + if (!sub) { + return false; + } + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const passArgs = Array.from(args); + if (payloadFunc) { + passArgs.push(payloadFunc(once ? null : listener)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + sub.stop(); + getInternal(contract).subs.delete(sub.tag); + } + return (count > 0); +} +async function emit(contract, event, args, payloadFunc) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payloadFunc); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +class BaseContract { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + target; + /** + * The contract Interface. + */ + interface; + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + runner; + /** + * All the Events available on this contract. + */ + filters; + /** + * @_ignore: + */ + [internal]; + /** + * The fallback or receive function if any. + */ + fallback; + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target, abi, runner, _deployTx) { + (0,errors/* assertArgument */.MR)(typeof (target) === "string" || (0,checks/* isAddressable */.$C)(target), "invalid value for Contract target", "target", target); + if (runner == null) { + runner = null; + } + const iface = abi_interface/* Interface */.KA.from(abi); + (0,properties/* defineProperties */.n)(this, { target, runner, interface: iface }); + Object.defineProperty(this, internal, { value: {} }); + let addrPromise; + let addr = null; + let deployTx = null; + if (_deployTx) { + const provider = getProvider(runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx); + } + let subs = new Map(); + // Resolve the target as the address + if (typeof (target) === "string") { + if ((0,data/* isHexString */.Lo)(target)) { + addr = target; + addrPromise = Promise.resolve(target); + } + else { + const resolver = getRunner(runner, "resolveName"); + if (!canResolve(resolver)) { + throw (0,errors/* makeError */.xz)("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw (0,errors/* makeError */.xz)("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { + value: target + }); + } + getInternal(this).addr = addr; + return addr; + }); + } + } + else { + addrPromise = target.getAddress().then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + getInternal(this).addr = addr; + return addr; + }); + } + // Set our private values + setInternal(this, { addrPromise, addr, deployTx, subs }); + // Add the event filters + const filters = new Proxy({}, { + get: (target, prop, receiver) => { + // Pass important checks (like `then` for Promise) through + if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + try { + return this.getEvent(prop); + } + catch (error) { + if (!(0,errors/* isError */.bJ)(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + // Pass important checks (like `then` for Promise) through + if (passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); + } + }); + (0,properties/* defineProperties */.n)(this, { filters }); + (0,properties/* defineProperties */.n)(this, { + fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null) + }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Undefined properties should return undefined + try { + return target.getFunction(prop); + } + catch (error) { + if (!(0,errors/* isError */.bJ)(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return target.interface.hasFunction(prop); + } + }); + } + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner) { + return new BaseContract(this.target, this.interface, runner); + } + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + /** + * Return the resolved address of this Contract. + */ + async getAddress() { return await getInternal(this).addrPromise; } + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + async getDeployedCode() { + const provider = getProvider(this.runner); + (0,errors/* assert */.vA)(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" }); + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + async waitForDeployment() { + // We have the deployement transaction; just use that (throws if deployement fails) + const deployTx = this.deploymentTransaction(); + if (deployTx) { + await deployTx.wait(); + return this; + } + // Check for code + const code = await this.getDeployedCode(); + if (code != null) { + return this; + } + // Make sure we can subscribe to a provider event + const provider = getProvider(this.runner); + (0,errors/* assert */.vA)(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }); + return new Promise((resolve, reject) => { + const checkCode = async () => { + try { + const code = await this.getDeployedCode(); + if (code != null) { + return resolve(this); + } + provider.once("block", checkCode); + } + catch (error) { + reject(error); + } + }; + checkCode(); + }); + } + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction() { + return getInternal(this).deployTx; + } + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + const func = buildWrappedMethod(this, key); + return func; + } + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return buildWrappedEvent(this, key); + } + /** + * @_ignore: + */ + async queryTransaction(hash) { + throw new Error("@TODO"); + } + /* + // @TODO: this is a non-backwards compatible change, but will be added + // in v7 and in a potential SmartContract class in an upcoming + // v6 release + async getTransactionReceipt(hash: string): Promise { + const provider = getProvider(this.runner); + assert(provider, "contract runner does not have a provider", + "UNSUPPORTED_OPERATION", { operation: "queryTransaction" }); + + const receipt = await provider.getTransactionReceipt(hash); + if (receipt == null) { return null; } + + return new ContractTransactionReceipt(this.interface, provider, receipt); + } + */ + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + async queryFilter(event, fromBlock, toBlock) { + if (fromBlock == null) { + fromBlock = 0; + } + if (toBlock == null) { + toBlock = "latest"; + } + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubInfo(this, event); + const filter = { address, topics, fromBlock, toBlock }; + const provider = getProvider(this.runner); + (0,errors/* assert */.vA)(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }); + return (await provider.getLogs(filter)).map((log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = this.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + if (foundFragment) { + try { + return new EventLog(log, this.interface, foundFragment); + } + catch (error) { + return new UndecodedEventLog(log, error); + } + } + return new providers_provider/* Log */.tG(log, provider); + }); + } + /** + * Add an event %%listener%% for the %%event%%. + */ + async on(event, listener) { + const sub = await getSub(this, "on", event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + async once(event, listener) { + const sub = await getSub(this, "once", event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + async emit(event, ...args) { + return await emit(this, event, args, null); + } + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + async listenerCount(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + const { subs } = getInternal(this); + let total = 0; + for (const { listeners } of subs.values()) { + total += listeners.length; + } + return total; + } + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + async listeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + const { subs } = getInternal(this); + let result = []; + for (const { listeners } of subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + async off(event, listener) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (listener == null || sub.listeners.length === 0) { + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + return this; + } + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + async removeAllListeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + else { + const { subs } = getInternal(this); + for (const { tag, stop } of subs.values()) { + stop(); + subs.delete(tag); + } + } + return this; + } + /** + * Alias for [on]. + */ + async addListener(event, listener) { + return await this.on(event, listener); + } + /** + * Alias for [off]. + */ + async removeListener(event, listener) { + return await this.off(event, listener); + } + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target, abi, runner) { + if (runner == null) { + runner = null; + } + const contract = new this(target, abi, runner); + return contract; + } +} +function _ContractBase() { + return BaseContract; +} +/** + * A [[BaseContract]] with no type guards on its methods or events. + */ +class Contract extends _ContractBase() { +} +//# sourceMappingURL=contract.js.map + +/***/ }), + +/***/ 8180: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + n1: () => (/* binding */ createHash), + Gz: () => (/* binding */ createHmac), + T_: () => (/* binding */ pbkdf2Sync), + po: () => (/* binding */ randomBytes) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/hmac.js +var hmac = __webpack_require__(4655); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/pbkdf2.js +var pbkdf2 = __webpack_require__(84877); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/sha256.js +var sha256 = __webpack_require__(3439); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_sha2.js +var _sha2 = __webpack_require__(37171); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_u64.js +var _u64 = __webpack_require__(86558); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/utils.js + 1 modules +var utils = __webpack_require__(10750); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/sha512.js + + + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64/* default.split */.Ay.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends _sha2/* SHA2 */.D { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = _u64/* default.rotrSH */.Ay.rotrSH(W15h, W15l, 1) ^ _u64/* default.rotrSH */.Ay.rotrSH(W15h, W15l, 8) ^ _u64/* default.shrSH */.Ay.shrSH(W15h, W15l, 7); + const s0l = _u64/* default.rotrSL */.Ay.rotrSL(W15h, W15l, 1) ^ _u64/* default.rotrSL */.Ay.rotrSL(W15h, W15l, 8) ^ _u64/* default.shrSL */.Ay.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = _u64/* default.rotrSH */.Ay.rotrSH(W2h, W2l, 19) ^ _u64/* default.rotrBH */.Ay.rotrBH(W2h, W2l, 61) ^ _u64/* default.shrSH */.Ay.shrSH(W2h, W2l, 6); + const s1l = _u64/* default.rotrSL */.Ay.rotrSL(W2h, W2l, 19) ^ _u64/* default.rotrBL */.Ay.rotrBL(W2h, W2l, 61) ^ _u64/* default.shrSL */.Ay.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = _u64/* default.add4L */.Ay.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = _u64/* default.add4H */.Ay.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = _u64/* default.rotrSH */.Ay.rotrSH(Eh, El, 14) ^ _u64/* default.rotrSH */.Ay.rotrSH(Eh, El, 18) ^ _u64/* default.rotrBH */.Ay.rotrBH(Eh, El, 41); + const sigma1l = _u64/* default.rotrSL */.Ay.rotrSL(Eh, El, 14) ^ _u64/* default.rotrSL */.Ay.rotrSL(Eh, El, 18) ^ _u64/* default.rotrBL */.Ay.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = _u64/* default.add5L */.Ay.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = _u64/* default.add5H */.Ay.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = _u64/* default.rotrSH */.Ay.rotrSH(Ah, Al, 28) ^ _u64/* default.rotrBH */.Ay.rotrBH(Ah, Al, 34) ^ _u64/* default.rotrBH */.Ay.rotrBH(Ah, Al, 39); + const sigma0l = _u64/* default.rotrSL */.Ay.rotrSL(Ah, Al, 28) ^ _u64/* default.rotrBL */.Ay.rotrBL(Ah, Al, 34) ^ _u64/* default.rotrBL */.Ay.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = _u64/* default.add */.Ay.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = _u64/* default.add3L */.Ay.add3L(T1l, sigma0l, MAJl); + Ah = _u64/* default.add3H */.Ay.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = _u64/* default.add */.Ay.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = _u64/* default.add */.Ay.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = _u64/* default.add */.Ay.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = _u64/* default.add */.Ay.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = _u64/* default.add */.Ay.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = _u64/* default.add */.Ay.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = _u64/* default.add */.Ay.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = _u64/* default.add */.Ay.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_224 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x8c3d37c8 | 0; + this.Al = 0x19544da2 | 0; + this.Bh = 0x73e19966 | 0; + this.Bl = 0x89dcd4d6 | 0; + this.Ch = 0x1dfab7ae | 0; + this.Cl = 0x32ff9c82 | 0; + this.Dh = 0x679dd514 | 0; + this.Dl = 0x582f9fcf | 0; + this.Eh = 0x0f6d2b69 | 0; + this.El = 0x7bd44da8 | 0; + this.Fh = 0x77e36f73 | 0; + this.Fl = 0x04c48942 | 0; + this.Gh = 0x3f9d85a8 | 0; + this.Gl = 0x6a1d36c8 | 0; + this.Hh = 0x1112e6ad | 0; + this.Hl = 0x91d692a1 | 0; + this.outputLen = 28; + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512 = /* @__PURE__ */ (0,utils/* wrapConstructor */.ld)(() => new SHA512()); +const sha512_224 = /* @__PURE__ */ (/* unused pure expression or super */ null && (wrapConstructor(() => new SHA512_224()))); +const sha512_256 = /* @__PURE__ */ (/* unused pure expression or super */ null && (wrapConstructor(() => new SHA512_256()))); +const sha384 = /* @__PURE__ */ (/* unused pure expression or super */ null && (wrapConstructor(() => new SHA384()))); +//# sourceMappingURL=sha512.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/crypto-browser.js +/* Browser Crypto Shims */ + + + + + +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const anyGlobal = getGlobal(); +const crypto_browser_crypto = anyGlobal.crypto || anyGlobal.msCrypto; +function createHash(algo) { + switch (algo) { + case "sha256": return sha256/* sha256 */.s.create(); + case "sha512": return sha512.create(); + } + (0,errors/* assertArgument */.MR)(false, "invalid hashing algorithm name", "algorithm", algo); +} +function createHmac(_algo, key) { + const algo = ({ sha256: sha256/* sha256 */.s, sha512: sha512 }[_algo]); + (0,errors/* assertArgument */.MR)(algo != null, "invalid hmac algorithm", "algorithm", _algo); + return hmac/* hmac */.w.create(algo, key); +} +function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = ({ sha256: sha256/* sha256 */.s, sha512: sha512 }[_algo]); + (0,errors/* assertArgument */.MR)(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo); + return (0,pbkdf2/* pbkdf2 */.A)(algo, password, salt, { c: iterations, dkLen: keylen }); +} +function randomBytes(length) { + (0,errors/* assert */.vA)(crypto_browser_crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + (0,errors/* assertArgument */.MR)(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length); + const result = new Uint8Array(length); + crypto_browser_crypto.getRandomValues(result); + return result; +} +//# sourceMappingURL=crypto-browser.js.map + +/***/ }), + +/***/ 15539: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + S: () => (/* binding */ keccak256) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_assert.js +var _assert = __webpack_require__(27125); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/_u64.js +var _u64 = __webpack_require__(86558); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/utils.js + 1 modules +var utils = __webpack_require__(10750); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/sha3.js + + + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0,_u64/* split */.lD)(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? (0,_u64/* rotlBH */.WM)(h, l, s) : (0,_u64/* rotlSH */.P5)(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? (0,_u64/* rotlBL */.im)(h, l, s) : (0,_u64/* rotlSL */.B4)(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends utils/* Hash */.Vw { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + (0,_assert/* number */.ai)(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = (0,utils/* u32 */.DH)(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + (0,_assert/* exists */.t2)(this); + const { blockLen, state } = this; + data = (0,utils/* toBytes */.ZJ)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + (0,_assert/* exists */.t2)(this, false); + (0,_assert/* bytes */.ee)(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + (0,_assert/* number */.ai)(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + (0,_assert/* output */.CG)(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => (0,utils/* wrapConstructor */.ld)(() => new Keccak(blockLen, suffix, outputLen)); +const sha3_224 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x06, 144, 224 / 8))); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x06, 136, 256 / 8))); +const sha3_384 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x06, 104, 384 / 8))); +const sha3_512 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x06, 72, 512 / 8))); +const keccak_224 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x01, 144, 224 / 8))); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); +const keccak_384 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x01, 104, 384 / 8))); +const keccak_512 = /* @__PURE__ */ (/* unused pure expression or super */ null && (gen(0x01, 72, 512 / 8))); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake128 = /* @__PURE__ */ (/* unused pure expression or super */ null && (genShake(0x1f, 168, 128 / 8))); +const shake256 = /* @__PURE__ */ (/* unused pure expression or super */ null && (genShake(0x1f, 136, 256 / 8))); +//# sourceMappingURL=sha3.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var utils_data = __webpack_require__(36212); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/keccak.js +/** + * Cryptographic hashing functions + * + * @_subsection: api/crypto:Hash Functions [about-crypto-hashing] + */ + + +let locked = false; +const _keccak256 = function (data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +/** + * Compute the cryptographic KECCAK256 hash of %%data%%. + * + * The %%data%% **must** be a data representation, to compute the + * hash of UTF-8 data use the [[id]] function. + * + * @returns DataHexstring + * @example: + * keccak256("0x") + * //_result: + * + * keccak256("0x1337") + * //_result: + * + * keccak256(new Uint8Array([ 0x13, 0x37 ])) + * //_result: + * + * // Strings are assumed to be DataHexString, otherwise it will + * // throw. To hash UTF-8 data, see the note above. + * keccak256("Hello World") + * //_error: + */ +function keccak256(_data) { + const data = (0,utils_data/* getBytes */.q5)(_data, "data"); + return (0,utils_data/* hexlify */.c$)(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function () { locked = true; }; +keccak256.register = function (func) { + if (locked) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); +//# sourceMappingURL=keccak.js.map + +/***/ }), + +/***/ 29851: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ pbkdf2) +/* harmony export */ }); +/* harmony import */ var _crypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8180); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36212); +/** + * A **Password-Based Key-Derivation Function** is designed to create + * a sequence of bytes suitible as a **key** from a human-rememberable + * password. + * + * @_subsection: api/crypto:Passwords [about-pbkdf] + */ + + +let locked = false; +const _pbkdf2 = function (password, salt, iterations, keylen, algo) { + return (0,_crypto_js__WEBPACK_IMPORTED_MODULE_0__/* .pbkdf2Sync */ .T_)(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +/** + * Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using + * the %%salt%% and using %%iterations%% of %%algo%%. + * + * This PBKDF is outdated and should not be used in new projects, but is + * required to decrypt older files. + * + * @example: + * // The password must be converted to bytes, and it is generally + * // best practices to ensure the string has been normalized. Many + * // formats explicitly indicate the normalization form to use. + * password = "hello" + * passwordBytes = toUtf8Bytes(password, "NFKC") + * + * salt = id("some-salt") + * + * // Compute the PBKDF2 + * pbkdf2(passwordBytes, salt, 1024, 16, "sha256") + * //_result: + */ +function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getBytes */ .q5)(_password, "password"); + const salt = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getBytes */ .q5)(_salt, "salt"); + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)(__pbkdf2(password, salt, iterations, keylen, algo)); +} +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function () { locked = true; }; +pbkdf2.register = function (func) { + if (locked) { + throw new Error("pbkdf2 is locked"); + } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); +//# sourceMappingURL=pbkdf2.js.map + +/***/ }), + +/***/ 68650: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ s: () => (/* binding */ sha256) +/* harmony export */ }); +/* unused harmony export sha512 */ +/* harmony import */ var _crypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8180); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36212); + + +const _sha256 = function (data) { + return (0,_crypto_js__WEBPACK_IMPORTED_MODULE_0__/* .createHash */ .n1)("sha256").update(data).digest(); +}; +const _sha512 = function (data) { + return (0,_crypto_js__WEBPACK_IMPORTED_MODULE_0__/* .createHash */ .n1)("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +/** + * Compute the cryptographic SHA2-256 hash of %%data%%. + * + * @_docloc: api/crypto:Hash Functions + * @returns DataHexstring + * + * @example: + * sha256("0x") + * //_result: + * + * sha256("0x1337") + * //_result: + * + * sha256(new Uint8Array([ 0x13, 0x37 ])) + * //_result: + * + */ +function sha256(_data) { + const data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getBytes */ .q5)(_data, "data"); + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)(__sha256(data)); +} +sha256._ = _sha256; +sha256.lock = function () { locked256 = true; }; +sha256.register = function (func) { + if (locked256) { + throw new Error("sha256 is locked"); + } + __sha256 = func; +}; +Object.freeze(sha256); +/** + * Compute the cryptographic SHA2-512 hash of %%data%%. + * + * @_docloc: api/crypto:Hash Functions + * @returns DataHexstring + * + * @example: + * sha512("0x") + * //_result: + * + * sha512("0x1337") + * //_result: + * + * sha512(new Uint8Array([ 0x13, 0x37 ])) + * //_result: + */ +function sha512(_data) { + const data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getBytes */ .q5)(_data, "data"); + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)(__sha512(data)); +} +sha512._ = _sha512; +sha512.lock = function () { locked512 = true; }; +sha512.register = function (func) { + if (locked512) { + throw new Error("sha512 is locked"); + } + __sha512 = func; +}; +Object.freeze(sha256); +//# sourceMappingURL=sha2.js.map + +/***/ }), + +/***/ 20260: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + t: () => (/* binding */ Signature) +}); + +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/constants/hashes.js +/** + * A constant for the zero hash. + * + * (**i.e.** ``"0x0000000000000000000000000000000000000000000000000000000000000000"``) + */ +const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +//# sourceMappingURL=hashes.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var data = __webpack_require__(36212); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/signature.js + + +// Constants +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const _guard = {}; +function toUint256(value) { + return (0,data/* zeroPadValue */.nx)((0,maths/* toBeArray */.c4)(value), 32); +} +/** + * A Signature @TODO + * + * + * @_docloc: api/crypto:Signing + */ +class Signature { + #r; + #s; + #v; + #networkV; + /** + * The ``r`` value for a signautre. + * + * This represents the ``x`` coordinate of a "reference" or + * challenge point, from which the ``y`` can be computed. + */ + get r() { return this.#r; } + set r(value) { + (0,errors/* assertArgument */.MR)((0,data/* dataLength */.pO)(value) === 32, "invalid r", "value", value); + this.#r = (0,data/* hexlify */.c$)(value); + } + /** + * The ``s`` value for a signature. + */ + get s() { return this.#s; } + set s(_value) { + (0,errors/* assertArgument */.MR)((0,data/* dataLength */.pO)(_value) === 32, "invalid s", "value", _value); + const value = (0,data/* hexlify */.c$)(_value); + (0,errors/* assertArgument */.MR)(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value); + this.#s = value; + } + /** + * The ``v`` value for a signature. + * + * Since a given ``x`` value for ``r`` has two possible values for + * its correspondin ``y``, the ``v`` indicates which of the two ``y`` + * values to use. + * + * It is normalized to the values ``27`` or ``28`` for legacy + * purposes. + */ + get v() { return this.#v; } + set v(value) { + const v = (0,maths/* getNumber */.WZ)(value, "value"); + (0,errors/* assertArgument */.MR)(v === 27 || v === 28, "invalid v", "v", value); + this.#v = v; + } + /** + * The EIP-155 ``v`` for legacy transactions. For non-legacy + * transactions, this value is ``null``. + */ + get networkV() { return this.#networkV; } + /** + * The chain ID for EIP-155 legacy transactions. For non-legacy + * transactions, this value is ``null``. + */ + get legacyChainId() { + const v = this.networkV; + if (v == null) { + return null; + } + return Signature.getChainId(v); + } + /** + * The ``yParity`` for the signature. + * + * See ``v`` for more details on how this value is used. + */ + get yParity() { + return (this.v === 27) ? 0 : 1; + } + /** + * The [[link-eip-2098]] compact representation of the ``yParity`` + * and ``s`` compacted into a single ``bytes32``. + */ + get yParityAndS() { + // The EIP-2098 compact representation + const yParityAndS = (0,data/* getBytes */.q5)(this.s); + if (this.yParity) { + yParityAndS[0] |= 0x80; + } + return (0,data/* hexlify */.c$)(yParityAndS); + } + /** + * The [[link-eip-2098]] compact representation. + */ + get compactSerialized() { + return (0,data/* concat */.xW)([this.r, this.yParityAndS]); + } + /** + * The serialized representation. + */ + get serialized() { + return (0,data/* concat */.xW)([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]); + } + /** + * @private + */ + constructor(guard, r, s, v) { + (0,errors/* assertPrivate */.gk)(guard, _guard, "Signature"); + this.#r = r; + this.#s = s; + this.#v = v; + this.#networkV = null; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + /** + * Returns a new identical [[Signature]]. + */ + clone() { + const clone = new Signature(_guard, this.r, this.s, this.v); + if (this.networkV) { + clone.#networkV = this.networkV; + } + return clone; + } + /** + * Returns a representation that is compatible with ``JSON.stringify``. + */ + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: ((networkV != null) ? networkV.toString() : null), + r: this.r, s: this.s, v: this.v, + }; + } + /** + * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions. + * + * @example: + * Signature.getChainId(45) + * //_result: + * + * Signature.getChainId(46) + * //_result: + */ + static getChainId(v) { + const bv = (0,maths/* getBigInt */.Ab)(v, "v"); + // The v is not an EIP-155 v, so it is the unspecified chain ID + if ((bv == BN_27) || (bv == BN_28)) { + return BN_0; + } + // Bad value for an EIP-155 v + (0,errors/* assertArgument */.MR)(bv >= BN_35, "invalid EIP-155 v", "v", v); + return (bv - BN_35) / BN_2; + } + /** + * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions. + * + * Legacy transactions which use [[link-eip-155]] hijack the ``v`` + * property to include the chain ID. + * + * @example: + * Signature.getChainIdV(5, 27) + * //_result: + * + * Signature.getChainIdV(5, 28) + * //_result: + * + */ + static getChainIdV(chainId, v) { + return ((0,maths/* getBigInt */.Ab)(chainId) * BN_2) + BigInt(35 + v - 27); + } + /** + * Compute the normalized legacy transaction ``v`` from a ``yParirty``, + * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction. + * + * @example: + * // The values 0 and 1 imply v is actually yParity + * Signature.getNormalizedV(0) + * //_result: + * + * // Legacy non-EIP-1559 transaction (i.e. 27 or 28) + * Signature.getNormalizedV(27) + * //_result: + * + * // Legacy EIP-155 transaction (i.e. >= 35) + * Signature.getNormalizedV(46) + * //_result: + * + * // Invalid values throw + * Signature.getNormalizedV(5) + * //_error: + */ + static getNormalizedV(v) { + const bv = (0,maths/* getBigInt */.Ab)(v); + if (bv === BN_0 || bv === BN_27) { + return 27; + } + if (bv === BN_1 || bv === BN_28) { + return 28; + } + (0,errors/* assertArgument */.MR)(bv >= BN_35, "invalid v", "v", v); + // Otherwise, EIP-155 v means odd is 27 and even is 28 + return (bv & BN_1) ? 27 : 28; + } + /** + * Creates a new [[Signature]]. + * + * If no %%sig%% is provided, a new [[Signature]] is created + * with default values. + * + * If %%sig%% is a string, it is parsed. + */ + static from(sig) { + function assertError(check, message) { + (0,errors/* assertArgument */.MR)(check, message, "signature", sig); + } + ; + if (sig == null) { + return new Signature(_guard, ZeroHash, ZeroHash, 27); + } + if (typeof (sig) === "string") { + const bytes = (0,data/* getBytes */.q5)(sig, "signature"); + if (bytes.length === 64) { + const r = (0,data/* hexlify */.c$)(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + const v = (s[0] & 0x80) ? 28 : 27; + s[0] &= 0x7f; + return new Signature(_guard, r, (0,data/* hexlify */.c$)(s), v); + } + if (bytes.length === 65) { + const r = (0,data/* hexlify */.c$)(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + assertError((s[0] & 0x80) === 0, "non-canonical s"); + const v = Signature.getNormalizedV(bytes[64]); + return new Signature(_guard, r, (0,data/* hexlify */.c$)(s), v); + } + assertError(false, "invalid raw signature length"); + } + if (sig instanceof Signature) { + return sig.clone(); + } + // Get r + const _r = sig.r; + assertError(_r != null, "missing r"); + const r = toUint256(_r); + // Get s; by any means necessary (we check consistency below) + const s = (function (s, yParityAndS) { + if (s != null) { + return toUint256(s); + } + if (yParityAndS != null) { + assertError((0,data/* isHexString */.Lo)(yParityAndS, 32), "invalid yParityAndS"); + const bytes = (0,data/* getBytes */.q5)(yParityAndS); + bytes[0] &= 0x7f; + return (0,data/* hexlify */.c$)(bytes); + } + assertError(false, "missing s"); + })(sig.s, sig.yParityAndS); + assertError(((0,data/* getBytes */.q5)(s)[0] & 0x80) == 0, "non-canonical s"); + // Get v; by any means necessary (we check consistency below) + const { networkV, v } = (function (_v, yParityAndS, yParity) { + if (_v != null) { + const v = (0,maths/* getBigInt */.Ab)(_v); + return { + networkV: ((v >= BN_35) ? v : undefined), + v: Signature.getNormalizedV(v) + }; + } + if (yParityAndS != null) { + assertError((0,data/* isHexString */.Lo)(yParityAndS, 32), "invalid yParityAndS"); + return { v: (((0,data/* getBytes */.q5)(yParityAndS)[0] & 0x80) ? 28 : 27) }; + } + if (yParity != null) { + switch ((0,maths/* getNumber */.WZ)(yParity, "sig.yParity")) { + case 0: return { v: 27 }; + case 1: return { v: 28 }; + } + assertError(false, "invalid yParity"); + } + assertError(false, "missing v"); + })(sig.v, sig.yParityAndS, sig.yParity); + const result = new Signature(_guard, r, s, v); + if (networkV) { + result.#networkV = networkV; + } + // If multiple of v, yParity, yParityAndS we given, check they match + assertError(sig.yParity == null || (0,maths/* getNumber */.WZ)(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch"); + assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch"); + return result; + } +} +//# sourceMappingURL=signature.js.map + +/***/ }), + +/***/ 15496: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + h: () => (/* binding */ SigningKey) +}); + +// NAMESPACE OBJECT: ./node_modules/ethers/node_modules/@noble/curves/esm/abstract/utils.js +var utils_namespaceObject = {}; +__webpack_require__.r(utils_namespaceObject); +__webpack_require__.d(utils_namespaceObject, { + OG: () => (bitMask), + My: () => (bytesToHex), + bytesToNumberBE: () => (utils_bytesToNumberBE), + lX: () => (utils_bytesToNumberLE), + Id: () => (utils_concatBytes), + fg: () => (createHmacDrbg), + qj: () => (utils_ensureBytes), + hexToBytes: () => (hexToBytes), + lq: () => (utils_numberToBytesBE), + z: () => (numberToBytesLE), + Q5: () => (validateObject) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/sha256.js +var esm_sha256 = __webpack_require__(3439); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/abstract/utils.js +/*! 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 = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const u8a = (a) => a instanceof Uint8Array; +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function utils_bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function utils_bytesToNumberLE(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function utils_numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return utils_numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(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 utils_ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (u8a(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 utils_concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +function equalBytes(b1, b2) { + // We don't care about timing attacks here + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(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(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, 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; +} +/** + * Sets single bit at position. + */ +const bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << 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 = (n) => (_2n << BigInt(n - 1)) - _1n; +// 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(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 utils_concatBytes(...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 = { + 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' || val instanceof Uint8Array, + 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 = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[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' }); +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/abstract/modular.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields + +// prettier-ignore +const modular_0n = BigInt(0), modular_1n = BigInt(1), modular_2n = BigInt(2), _3n = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +// prettier-ignore +const _9n = BigInt(9), _16n = BigInt(16); +// Calculates a modulo b +function modular_mod(a, b) { + const result = a % b; + return result >= modular_0n ? 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(num, power, modulo) { + if (modulo <= modular_0n || power < modular_0n) + throw new Error('Expected power/modulo > 0'); + if (modulo === modular_1n) + return modular_0n; + let res = modular_1n; + while (power > modular_0n) { + if (power & modular_1n) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= modular_1n; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > modular_0n) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +function invert(number, modulo) { + if (number === modular_0n || modulo <= modular_0n) { + 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 = modular_mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = modular_0n, y = modular_1n, u = modular_1n, v = modular_0n; + while (a !== modular_0n) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== modular_1n) + throw new Error('invert: does not exist'); + return modular_mod(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(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 - modular_1n) / modular_2n; + 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 - modular_1n, S = 0; Q % modular_2n === modular_0n; Q /= modular_2n, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = modular_2n; Z < P && pow(Z, legendreC, P) !== P - modular_1n; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + modular_1n) / _4n; + 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 + modular_1n) / modular_2n; + 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, modular_1n << 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(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 === _3n) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + modular_1n) / _4n; + 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 === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, modular_2n); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, modular_2n), 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; + }; + } + // P ≡ 9 (mod 16) + if (P % _16n === _9n) { + // NOTE: tonelli is too slow for bls-Fp2 calculations even on start + // Means we cannot use sqrt for constants at all! + // + // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + // sqrt = (x) => { + // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4 + // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1 + // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1 + // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1 + // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x + // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x + // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x + // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2 + // } + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// Little-endian check for first LE bit (last BE bit); +const isNegativeLE = (num, modulo) => (modular_mod(num, modulo) & modular_1n) === modular_1n; +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(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(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < modular_0n) + throw new Error('Expected power > 0'); + if (power === modular_0n) + return f.ONE; + if (power === modular_1n) + return num; + let p = f.ONE; + let d = num; + while (power > modular_0n) { + if (power & modular_1n) + p = f.mul(p, d); + d = f.sqr(d); + power >>= modular_1n; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(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; +} +function FpDiv(f, lhs, rhs) { + return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs)); +} +// This function returns True whenever the value x is a square in the field F. +function FpIsSquare(f) { + const legendreConst = (f.ORDER - modular_1n) / modular_2n; // Integer arithmetic + return (x) => { + const p = f.pow(x, legendreConst); + return f.eql(p, f.ZERO) || f.eql(p, f.ONE); + }; +} +// CURVE.n lengths +function nLength(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(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= modular_0n) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: modular_0n, + ONE: modular_1n, + create: (num) => modular_mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return modular_0n <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === modular_0n, + isOdd: (num) => (num & modular_1n) === modular_1n, + neg: (num) => modular_mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => modular_mod(num * num, ORDER), + add: (lhs, rhs) => modular_mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => modular_mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => modular_mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => modular_mod(lhs * invert(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(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(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(num, BYTES) : utils_numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? utils_bytesToNumberLE(bytes) : utils_bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +function FpSqrtOdd(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? root : Fp.neg(root); +} +function FpSqrtEven(Fp, elm) { + if (!Fp.isOdd) + throw new Error(`Field doesn't have isOdd`); + const root = Fp.sqrt(elm); + return Fp.isOdd(root) ? Fp.neg(root) : root; +} +/** + * "Constant-time" private key generation utility. + * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field). + * Which makes it slightly more biased, less secure. + * @deprecated use mapKeyToField instead + */ +function hashToPrivateScalar(hash, groupOrder, isLE = false) { + hash = ensureBytes('privateHash', hash); + const hashLen = hash.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash); + return modular_mod(num, groupOrder - modular_1n) + modular_1n; +} +/** + * 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') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? utils_bytesToNumberBE(key) : utils_bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = modular_mod(num, fieldOrder - modular_1n) + modular_1n; + return isLE ? numberToBytesLE(reduced, fieldLen) : utils_numberToBytesBE(reduced, fieldLen); +} +//# sourceMappingURL=modular.js.map +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/hmac.js +var hmac = __webpack_require__(4655); +// EXTERNAL MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/utils.js + 1 modules +var utils = __webpack_require__(10750); +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/abstract/curve.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities + + +const curve_0n = BigInt(0); +const curve_1n = BigInt(1); +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > curve_0n) { + if (n & curve_1n) + p = p.add(d); + d = d.double(); + n >>= curve_1n; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += curve_1n; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, precomputesMap, n, transform) { + // @ts-ignore + const W = P._WINDOW_SIZE || 1; + // Calculate precomputes on a first run, reuse them after + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} +//# sourceMappingURL=curve.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/abstract/weierstrass.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b + + + + +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +// ASN.1 DER encoding utilities +const { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_namespaceObject; +const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 0x02) + throw new E('Invalid signature integer tag'); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E('Invalid signature integer: wrong length'); + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + if (res[0] & 0b10000000) + throw new E('Invalid signature integer: negative'); + if (res[0] === 0x00 && !(res[1] & 0b10000000)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left + }, + toSig(hex) { + // parse DER signature + const { Err: E } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error('ui8a expected'); + let l = data.length; + if (l < 2 || data[0] != 0x30) + throw new E('Invalid signature tag'); + if (data[1] !== l - 2) + throw new E('Invalid signature: incorrect length'); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r, s }; + }, + hexFromSig(sig) { + // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' + const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); + const h = (num) => { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const weierstrass_0n = BigInt(0), weierstrass_1n = BigInt(1), weierstrass_2n = BigInt(2), weierstrass_3n = BigInt(3), weierstrass_4n = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return utils_concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return typeof num === 'bigint' && weierstrass_0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error('Expected valid bigint: 0 < bigint < curve.n'); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (key instanceof Uint8Array) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : utils_bytesToNumberBE(utils_ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = modular_mod(num, n); // disabled by default, enabled for BLS + assertGE(num); // num in range [1..N-1] + return num; + } + const pointPrecomputes = new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(utils_ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = this.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!this.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, weierstrass_3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, weierstrass_3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === weierstrass_0n) + return I; + assertGE(n); // Will throw on 0 + if (n === weierstrass_1n) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > weierstrass_0n || k2 > weierstrass_0n) { + if (k1 & weierstrass_1n) + k1p = k1p.add(d); + if (k2 & weierstrass_1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= weierstrass_1n; + k2 >>= weierstrass_1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; // Fake point is used to const-time mult + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === weierstrass_0n || a === weierstrass_1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === weierstrass_1n) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === weierstrass_1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function isValidFieldElement(num) { + return weierstrass_0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE + } + function modN(a) { + return modular_mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = utils_concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = utils_bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + const isYOdd = (y & weierstrass_1n) === weierstrass_1n; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(utils_numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> weierstrass_1n; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => utils_bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = utils_ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(utils_ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + // can use assertGE here + if (!isWithinCurveOrder(this.r)) + throw new Error('r must be 0 < r < CURVE.n'); + if (!isWithinCurveOrder(this.s)) + throw new Error('s must be 0 < s < CURVE.n'); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(utils_ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = utils_bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('bigint expected'); + if (!(weierstrass_0n <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + // works with order, can have different size than numToField! + return utils_numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = utils_ensureBytes('msgHash', msgHash); + if (prehash) + msgHash = utils_ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(utils_ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = utils_concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === weierstrass_0n) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === weierstrass_0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & weierstrass_1n); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = utils_ensureBytes('msgHash', msgHash); + publicKey = utils_ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || sg instanceof Uint8Array) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * @param Fp + * @param Z + * @returns + */ +function SWUFpSqrtRatio(Fp, Z) { + // Generic implementation + const q = Fp.ORDER; + let l = weierstrass_0n; + for (let o = q - weierstrass_1n; o % weierstrass_2n === weierstrass_0n; o /= weierstrass_2n) + l += weierstrass_1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = weierstrass_2n << (c1 - weierstrass_1n - weierstrass_1n); + const _2n_pow_c1 = _2n_pow_c1_1 * weierstrass_2n; + const c2 = (q - weierstrass_1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - weierstrass_1n) / weierstrass_2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - weierstrass_1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = Fp.pow(Z, (c2 + weierstrass_1n) / weierstrass_2n); // 7. c7 = Z^((c2 + 1) / 2) + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1 + tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > weierstrass_1n; i--) { + let tv5 = i - weierstrass_2n; // 18. tv5 = i - 2 + tv5 = weierstrass_2n << (tv5 - weierstrass_1n); // 19. tv5 = 2^tv5 + let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1 + tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % weierstrass_4n === weierstrass_3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (Fp.ORDER - weierstrass_3n) / weierstrass_4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); // 1. tv1 = v^2 + const tv2 = Fp.mul(u, v); // 2. tv2 = u * v + tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u + let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 + */ +function weierstrass_mapToCurveSimpleSWU(Fp, opts) { + mod.validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error('Fp.isOdd is not implemented!'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1 + tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1 + tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3 + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4 + tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6 + tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6 + tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = Fp.mul(y, value); // 20. y = y * y1 + x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + x = Fp.div(x, tv4); // 25. x = x / tv4 + return { x, y }; + }; +} +//# sourceMappingURL=weierstrass.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/_shortw_utils.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + + + +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => (0,hmac/* hmac */.w)(hash, key, (0,utils/* concatBytes */.Id)(...msgs)), + randomBytes: utils/* randomBytes */.po, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} +//# sourceMappingURL=_shortw_utils.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/curves/esm/secp256k1.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + + + + + + + +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const secp256k1_1n = BigInt(1); +const secp256k1_2n = BigInt(2); +const divNearest = (a, b) => (a + b / secp256k1_2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, secp256k1_2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, secp256k1_2n, P); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -secp256k1_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = modular_mod(k - c1 * a1 - c2 * a2, n); + let k2 = modular_mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, esm_sha256/* sha256 */.s); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +const secp256k1_0n = BigInt(0); +const fe = (x) => typeof x === 'bigint' && secp256k1_0n < x && x < secp256k1P; +const ge = (x) => typeof x === 'bigint' && secp256k1_0n < x && x < secp256k1N; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toRawBytes(true).slice(1); +const numTo32b = (n) => numberToBytesBE(n, 32); +const modP = (x) => mod(x, secp256k1P); +const modN = (x) => mod(x, secp256k1N); +const Point = secp256k1.ProjectivePoint; +const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey + let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar: scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + if (!fe(x)) + throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. + if (y % secp256k1_2n !== secp256k1_0n) + y = modP(-y); // Return the unique point P such that x(P) = x and + const p = new Point(x, y, secp256k1_1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + p.assertValidity(); + return p; +} +/** + * Create tagged hash, convert it to bigint, reduce modulo-n. + */ +function challenge(...args) { + return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args))); +} +/** + * Schnorr public key is just `x` coordinate of Point as per BIP340. + */ +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. + */ +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes('message', message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder + const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array + const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n + if (k_ === secp256k1_0n) + throw new Error('sign failed: k is zero'); // Fail if k' = 0. + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes('signature', signature, 64); + const m = ensureBytes('message', message); + const pub = ensureBytes('publicKey', publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails + const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n + const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; // -eP == (n-e)P + return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + } + catch (error) { + return false; + } +} +const schnorr = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, +}))())); +const isoMap = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => isogenyMap(Fp, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))())); +const mapSWU = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => mapToCurveSimpleSWU(Fp, { + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fp.create(BigInt('-11')), +}))())); +const htf = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fp.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))())); +const hashToCurve = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => htf.hashToCurve)())); +const encodeToCurve = /* @__PURE__ */ (/* unused pure expression or super */ null && ((() => htf.encodeToCurve)())); +//# sourceMappingURL=secp256k1.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var data = __webpack_require__(36212); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/signature.js + 1 modules +var crypto_signature = __webpack_require__(20260); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/crypto/signing-key.js +/** + * Add details about signing here. + * + * @_subsection: api/crypto:Signing [about-signing] + */ + + + +/** + * A **SigningKey** provides high-level access to the elliptic curve + * cryptography (ECC) operations and key management. + */ +class SigningKey { + #privateKey; + /** + * Creates a new **SigningKey** for %%privateKey%%. + */ + constructor(privateKey) { + (0,errors/* assertArgument */.MR)((0,data/* dataLength */.pO)(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]"); + this.#privateKey = (0,data/* hexlify */.c$)(privateKey); + } + /** + * The private key. + */ + get privateKey() { return this.#privateKey; } + /** + * The uncompressed public key. + * + * This will always begin with the prefix ``0x04`` and be 132 + * characters long (the ``0x`` prefix and 130 hexadecimal nibbles). + */ + get publicKey() { return SigningKey.computePublicKey(this.#privateKey); } + /** + * The compressed public key. + * + * This will always begin with either the prefix ``0x02`` or ``0x03`` + * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal + * nibbles) + */ + get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); } + /** + * Return the signature of the signed %%digest%%. + */ + sign(digest) { + (0,errors/* assertArgument */.MR)((0,data/* dataLength */.pO)(digest) === 32, "invalid digest length", "digest", digest); + const sig = secp256k1.sign((0,data/* getBytesCopy */.Lm)(digest), (0,data/* getBytesCopy */.Lm)(this.#privateKey), { + lowS: true + }); + return crypto_signature/* Signature */.t.from({ + r: (0,maths/* toBeHex */.up)(sig.r, 32), + s: (0,maths/* toBeHex */.up)(sig.s, 32), + v: (sig.recovery ? 0x1c : 0x1b) + }); + } + /** + * Returns the [[link-wiki-ecdh]] shared secret between this + * private key and the %%other%% key. + * + * The %%other%% key may be any type of key, a raw public key, + * a compressed/uncompressed pubic key or aprivate key. + * + * Best practice is usually to use a cryptographic hash on the + * returned value before using it as a symetric secret. + * + * @example: + * sign1 = new SigningKey(id("some-secret-1")) + * sign2 = new SigningKey(id("some-secret-2")) + * + * // Notice that privA.computeSharedSecret(pubB)... + * sign1.computeSharedSecret(sign2.publicKey) + * //_result: + * + * // ...is equal to privB.computeSharedSecret(pubA). + * sign2.computeSharedSecret(sign1.publicKey) + * //_result: + */ + computeSharedSecret(other) { + const pubKey = SigningKey.computePublicKey(other); + return (0,data/* hexlify */.c$)(secp256k1.getSharedSecret((0,data/* getBytesCopy */.Lm)(this.#privateKey), (0,data/* getBytes */.q5)(pubKey), false)); + } + /** + * Compute the public key for %%key%%, optionally %%compressed%%. + * + * The %%key%% may be any type of key, a raw public key, a + * compressed/uncompressed public key or private key. + * + * @example: + * sign = new SigningKey(id("some-secret")); + * + * // Compute the uncompressed public key for a private key + * SigningKey.computePublicKey(sign.privateKey) + * //_result: + * + * // Compute the compressed public key for a private key + * SigningKey.computePublicKey(sign.privateKey, true) + * //_result: + * + * // Compute the uncompressed public key + * SigningKey.computePublicKey(sign.publicKey, false); + * //_result: + * + * // Compute the Compressed a public key + * SigningKey.computePublicKey(sign.publicKey, true); + * //_result: + */ + static computePublicKey(key, compressed) { + let bytes = (0,data/* getBytes */.q5)(key, "key"); + // private key + if (bytes.length === 32) { + const pubKey = secp256k1.getPublicKey(bytes, !!compressed); + return (0,data/* hexlify */.c$)(pubKey); + } + // raw public key; use uncompressed key with 0x04 prefix + if (bytes.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 0x04; + pub.set(bytes, 1); + bytes = pub; + } + const point = secp256k1.ProjectivePoint.fromHex(bytes); + return (0,data/* hexlify */.c$)(point.toRawBytes(compressed)); + } + /** + * Returns the public key for the private key which produced the + * %%signature%% for the given %%digest%%. + * + * @example: + * key = new SigningKey(id("some-secret")) + * digest = id("hello world") + * sig = key.sign(digest) + * + * // Notice the signer public key... + * key.publicKey + * //_result: + * + * // ...is equal to the recovered public key + * SigningKey.recoverPublicKey(digest, sig) + * //_result: + * + */ + static recoverPublicKey(digest, signature) { + (0,errors/* assertArgument */.MR)((0,data/* dataLength */.pO)(digest) === 32, "invalid digest length", "digest", digest); + const sig = crypto_signature/* Signature */.t.from(signature); + let secpSig = secp256k1.Signature.fromCompact((0,data/* getBytesCopy */.Lm)((0,data/* concat */.xW)([sig.r, sig.s]))); + secpSig = secpSig.addRecoveryBit(sig.yParity); + const pubKey = secpSig.recoverPublicKey((0,data/* getBytesCopy */.Lm)(digest)); + (0,errors/* assertArgument */.MR)(pubKey != null, "invalid signautre for digest", "signature", signature); + return "0x" + pubKey.toHex(false); + } + /** + * Returns the point resulting from adding the ellipic curve points + * %%p0%% and %%p1%%. + * + * This is not a common function most developers should require, but + * can be useful for certain privacy-specific techniques. + * + * For example, it is used by [[HDNodeWallet]] to compute child + * addresses from parent public keys and chain codes. + */ + static addPoints(p0, p1, compressed) { + const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2)); + const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); + } +} +//# sourceMappingURL=signing-key.js.map + +/***/ }), + +/***/ 38264: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ id: () => (/* binding */ id) +/* harmony export */ }); +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15539); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87303); + + +/** + * A simple hashing function which operates on UTF-8 strings to + * compute an 32-byte identifier. + * + * This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes + * the [[keccak256]]. + * + * @example: + * id("hello world") + * //_result: + */ +function id(value) { + return (0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_0__/* .keccak256 */ .S)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .toUtf8Bytes */ .YW)(value)); +} +//# sourceMappingURL=id.js.map + +/***/ }), + +/***/ 64563: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Wh: () => (/* binding */ dnsEncode), + kM: () => (/* binding */ namehash) +}); + +// UNUSED EXPORTS: ensNormalize, isValidName + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/keccak.js + 1 modules +var keccak = __webpack_require__(15539); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/utf8.js +var utf8 = __webpack_require__(87303); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var data = __webpack_require__(36212); +;// CONCATENATED MODULE: ./node_modules/@adraffy/ens-normalize/dist/index.mjs +// created 2023-09-25T01:01:55.148Z +// compressed base64-encoded blob for include-ens data +// source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js +// see: https://github.com/adraffy/ens-normalize.js#security +// SHA-256: 0565ed049b9cf1614bb9e11ba7d8ac6a6fb96c893253d890f7e2b2884b9ded32 +var COMPRESSED$1 = 'AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI'; +const FENCED = new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]); +const NSM_MAX = 4; + +function decode_arithmetic(bytes) { + let pos = 0; + function u16() { return (bytes[pos++] << 8) | bytes[pos++]; } + + // decode the frequency table + let symbol_count = u16(); + let total = 1; + let acc = [0, 1]; // first symbol has frequency 1 + for (let i = 1; i < symbol_count; i++) { + acc.push(total += u16()); + } + + // skip the sized-payload that the last 3 symbols index into + let skip = u16(); + let pos_payload = pos; + pos += skip; + + let read_width = 0; + let read_buffer = 0; + function read_bit() { + if (read_width == 0) { + // this will read beyond end of buffer + // but (undefined|0) => zero pad + read_buffer = (read_buffer << 8) | bytes[pos++]; + read_width = 8; + } + return (read_buffer >> --read_width) & 1; + } + + const N = 31; + const FULL = 2**N; + const HALF = FULL >>> 1; + const QRTR = HALF >> 1; + const MASK = FULL - 1; + + // fill register + let register = 0; + for (let i = 0; i < N; i++) register = (register << 1) | read_bit(); + + let symbols = []; + let low = 0; + let range = FULL; // treat like a float + while (true) { + let value = Math.floor((((register - low + 1) * total) - 1) / range); + let start = 0; + let end = symbol_count; + while (end - start > 1) { // binary search + let mid = (start + end) >>> 1; + if (value < acc[mid]) { + end = mid; + } else { + start = mid; + } + } + if (start == 0) break; // first symbol is end mark + symbols.push(start); + let a = low + Math.floor(range * acc[start] / total); + let b = low + Math.floor(range * acc[start+1] / total) - 1; + while (((a ^ b) & HALF) == 0) { + register = (register << 1) & MASK | read_bit(); + a = (a << 1) & MASK; + b = (b << 1) & MASK | 1; + } + while (a & ~b & QRTR) { + register = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit(); + a = (a << 1) ^ HALF; + b = ((b ^ HALF) << 1) | HALF | 1; + } + low = a; + range = 1 + b - a; + } + let offset = symbol_count - 4; + return symbols.map(x => { // index into payload + switch (x - offset) { + case 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]); + case 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]); + case 1: return offset + bytes[pos_payload++]; + default: return x - 1; + } + }); +} + +// returns an iterator which returns the next symbol +function read_payload(v) { + let pos = 0; + return () => v[pos++]; +} +function read_compressed_payload(s) { + return read_payload(decode_arithmetic(unsafe_atob(s))); +} + +// unsafe in the sense: +// expected well-formed Base64 w/o padding +// 20220922: added for https://github.com/adraffy/ens-normalize.js/issues/4 +function unsafe_atob(s) { + let lookup = []; + [...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].forEach((c, i) => lookup[c.charCodeAt(0)] = i); + let n = s.length; + let ret = new Uint8Array((6 * n) >> 3); + for (let i = 0, pos = 0, width = 0, carry = 0; i < n; i++) { + carry = (carry << 6) | lookup[s.charCodeAt(i)]; + width += 6; + if (width >= 8) { + ret[pos++] = (carry >> (width -= 8)); + } + } + return ret; +} + +// eg. [0,1,2,3...] => [0,-1,1,-2,...] +function signed(i) { + return (i & 1) ? (~i >> 1) : (i >> 1); +} + +function read_deltas(n, next) { + let v = Array(n); + for (let i = 0, x = 0; i < n; i++) v[i] = x += signed(next()); + return v; +} + +// [123][5] => [0 3] [1 1] [0 0] +function read_sorted(next, prev = 0) { + let ret = []; + while (true) { + let x = next(); + let n = next(); + if (!n) break; + prev += x; + for (let i = 0; i < n; i++) { + ret.push(prev + i); + } + prev += n + 1; + } + return ret; +} + +function read_sorted_arrays(next) { + return read_array_while(() => { + let v = read_sorted(next); + if (v.length) return v; + }); +} + +// returns map of x => ys +function read_mapped(next) { + let ret = []; + while (true) { + let w = next(); + if (w == 0) break; + ret.push(read_linear_table(w, next)); + } + while (true) { + let w = next() - 1; + if (w < 0) break; + ret.push(read_replacement_table(w, next)); + } + return ret.flat(); +} + +// read until next is falsy +// return array of read values +function read_array_while(next) { + let v = []; + while (true) { + let x = next(v.length); + if (!x) break; + v.push(x); + } + return v; +} + +// read w columns of length n +// return as n rows of length w +function read_transposed(n, w, next) { + let m = Array(n).fill().map(() => []); + for (let i = 0; i < w; i++) { + read_deltas(n, next).forEach((x, j) => m[j].push(x)); + } + return m; +} + +// returns [[x, ys], [x+dx, ys+dy], [x+2*dx, ys+2*dy], ...] +// where dx/dy = steps, n = run size, w = length of y +function read_linear_table(w, next) { + let dx = 1 + next(); + let dy = next(); + let vN = read_array_while(next); + let m = read_transposed(vN.length, 1+w, next); + return m.flatMap((v, i) => { + let [x, ...ys] = v; + return Array(vN[i]).fill().map((_, j) => { + let j_dy = j * dy; + return [x + j * dx, ys.map(y => y + j_dy)]; + }); + }); +} + +// return [[x, ys...], ...] +// where w = length of y +function read_replacement_table(w, next) { + let n = 1 + next(); + let m = read_transposed(n, 1+w, next); + return m.map(v => [v[0], v.slice(1)]); +} + + +function read_trie(next) { + let ret = []; + let sorted = read_sorted(next); + expand(decode([]), []); + return ret; // not sorted + function decode(Q) { // characters that lead into this node + let S = next(); // state: valid, save, check + let B = read_array_while(() => { // buckets leading to new nodes + let cps = read_sorted(next).map(i => sorted[i]); + if (cps.length) return decode(cps); + }); + return {S, B, Q}; + } + function expand({S, B}, cps, saved) { + if (S & 4 && saved === cps[cps.length-1]) return; + if (S & 2) saved = cps[cps.length-1]; + if (S & 1) ret.push(cps); + for (let br of B) { + for (let cp of br.Q) { + expand(br, [...cps, cp], saved); + } + } + } +} + +function hex_cp(cp) { + return cp.toString(16).toUpperCase().padStart(2, '0'); +} + +function quote_cp(cp) { + return `{${hex_cp(cp)}}`; // raffy convention: like "\u{X}" w/o the "\u" +} + +/* +export function explode_cp(s) { + return [...s].map(c => c.codePointAt(0)); +} +*/ +function explode_cp(s) { // this is about 2x faster + let cps = []; + for (let pos = 0, len = s.length; pos < len; ) { + let cp = s.codePointAt(pos); + pos += cp < 0x10000 ? 1 : 2; + cps.push(cp); + } + return cps; +} + +function str_from_cps(cps) { + const chunk = 4096; + let len = cps.length; + if (len < chunk) return String.fromCodePoint(...cps); + let buf = []; + for (let i = 0; i < len; ) { + buf.push(String.fromCodePoint(...cps.slice(i, i += chunk))); + } + return buf.join(''); +} + +function compare_arrays(a, b) { + let n = a.length; + let c = n - b.length; + for (let i = 0; c == 0 && i < n; i++) c = a[i] - b[i]; + return c; +} + +// created 2023-09-25T01:01:55.148Z +// compressed base64-encoded blob for include-nf data +// source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js +// see: https://github.com/adraffy/ens-normalize.js#security +// SHA-256: a974b6f8541fc29d919bc85118af0a44015851fab5343f8679cb31be2bdb209e +var COMPRESSED = 'AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g'; + +// https://unicode.org/reports/tr15/ +// for reference implementation +// see: /derive/nf.js + + +// algorithmic hangul +// https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf (page 144) +const S0 = 0xAC00; +const L0 = 0x1100; +const V0 = 0x1161; +const T0 = 0x11A7; +const L_COUNT = 19; +const V_COUNT = 21; +const T_COUNT = 28; +const N_COUNT = V_COUNT * T_COUNT; +const S_COUNT = L_COUNT * N_COUNT; +const S1 = S0 + S_COUNT; +const L1 = L0 + L_COUNT; +const V1 = V0 + V_COUNT; +const T1 = T0 + T_COUNT; + +function unpack_cc(packed) { + return (packed >> 24) & 0xFF; +} +function unpack_cp(packed) { + return packed & 0xFFFFFF; +} + +let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP; + +function init$1() { + //console.time('nf'); + let r = read_compressed_payload(COMPRESSED); + SHIFTED_RANK = new Map(read_sorted_arrays(r).flatMap((v, i) => v.map(x => [x, (i+1) << 24]))); // pre-shifted + EXCLUSIONS = new Set(read_sorted(r)); + DECOMP = new Map(); + RECOMP = new Map(); + for (let [cp, cps] of read_mapped(r)) { + if (!EXCLUSIONS.has(cp) && cps.length == 2) { + let [a, b] = cps; + let bucket = RECOMP.get(a); + if (!bucket) { + bucket = new Map(); + RECOMP.set(a, bucket); + } + bucket.set(b, cp); + } + DECOMP.set(cp, cps.reverse()); // stored reversed + } + //console.timeEnd('nf'); + // 20230905: 11ms +} + +function is_hangul(cp) { + return cp >= S0 && cp < S1; +} + +function compose_pair(a, b) { + if (a >= L0 && a < L1 && b >= V0 && b < V1) { + return S0 + (a - L0) * N_COUNT + (b - V0) * T_COUNT; + } else if (is_hangul(a) && b > T0 && b < T1 && (a - S0) % T_COUNT == 0) { + return a + (b - T0); + } else { + let recomp = RECOMP.get(a); + if (recomp) { + recomp = recomp.get(b); + if (recomp) { + return recomp; + } + } + return -1; + } +} + +function decomposed(cps) { + if (!SHIFTED_RANK) init$1(); + let ret = []; + let buf = []; + let check_order = false; + function add(cp) { + let cc = SHIFTED_RANK.get(cp); + if (cc) { + check_order = true; + cp |= cc; + } + ret.push(cp); + } + for (let cp of cps) { + while (true) { + if (cp < 0x80) { + ret.push(cp); + } else if (is_hangul(cp)) { + let s_index = cp - S0; + let l_index = s_index / N_COUNT | 0; + let v_index = (s_index % N_COUNT) / T_COUNT | 0; + let t_index = s_index % T_COUNT; + add(L0 + l_index); + add(V0 + v_index); + if (t_index > 0) add(T0 + t_index); + } else { + let mapped = DECOMP.get(cp); + if (mapped) { + buf.push(...mapped); + } else { + add(cp); + } + } + if (!buf.length) break; + cp = buf.pop(); + } + } + if (check_order && ret.length > 1) { + let prev_cc = unpack_cc(ret[0]); + for (let i = 1; i < ret.length; i++) { + let cc = unpack_cc(ret[i]); + if (cc == 0 || prev_cc <= cc) { + prev_cc = cc; + continue; + } + let j = i-1; + while (true) { + let tmp = ret[j+1]; + ret[j+1] = ret[j]; + ret[j] = tmp; + if (!j) break; + prev_cc = unpack_cc(ret[--j]); + if (prev_cc <= cc) break; + } + prev_cc = unpack_cc(ret[i]); + } + } + return ret; +} + +function composed_from_decomposed(v) { + let ret = []; + let stack = []; + let prev_cp = -1; + let prev_cc = 0; + for (let packed of v) { + let cc = unpack_cc(packed); + let cp = unpack_cp(packed); + if (prev_cp == -1) { + if (cc == 0) { + prev_cp = cp; + } else { + ret.push(cp); + } + } else if (prev_cc > 0 && prev_cc >= cc) { + if (cc == 0) { + ret.push(prev_cp, ...stack); + stack.length = 0; + prev_cp = cp; + } else { + stack.push(cp); + } + prev_cc = cc; + } else { + let composed = compose_pair(prev_cp, cp); + if (composed >= 0) { + prev_cp = composed; + } else if (prev_cc == 0 && cc == 0) { + ret.push(prev_cp); + prev_cp = cp; + } else { + stack.push(cp); + prev_cc = cc; + } + } + } + if (prev_cp >= 0) { + ret.push(prev_cp, ...stack); + } + return ret; +} + +// note: cps can be iterable +function nfd(cps) { + return decomposed(cps).map(unpack_cp); +} +function nfc(cps) { + return composed_from_decomposed(decomposed(cps)); +} + +const HYPHEN = 0x2D; +const STOP = 0x2E; +const STOP_CH = '.'; +const FE0F = 0xFE0F; +const UNIQUE_PH = 1; + +// 20230913: replace [...v] with Array_from(v) to avoid large spreads +const Array_from = x => Array.from(x); // Array.from.bind(Array); + +function group_has_cp(g, cp) { + // 20230913: keep primary and secondary distinct instead of creating valid union + return g.P.has(cp) || g.Q.has(cp); +} + +class Emoji extends Array { + get is_emoji() { return true; } // free tagging system +} + +let MAPPED, IGNORED, CM, NSM, ESCAPE, NFC_CHECK, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT; + +function init() { + if (MAPPED) return; + + let r = read_compressed_payload(COMPRESSED$1); + const read_sorted_array = () => read_sorted(r); + const read_sorted_set = () => new Set(read_sorted_array()); + const set_add_many = (set, v) => v.forEach(x => set.add(x)); + + MAPPED = new Map(read_mapped(r)); + IGNORED = read_sorted_set(); // ignored characters are not valid, so just read raw codepoints + + /* + // direct include from payload is smaller than the decompression code + const FENCED = new Map(read_array_while(() => { + let cp = r(); + if (cp) return [cp, read_str(r())]; + })); + */ + // 20230217: we still need all CM for proper error formatting + // but norm only needs NSM subset that are potentially-valid + CM = read_sorted_array(); + NSM = new Set(read_sorted_array().map(i => CM[i])); + CM = new Set(CM); + + ESCAPE = read_sorted_set(); // characters that should not be printed + NFC_CHECK = read_sorted_set(); // only needed to illustrate ens_tokenize() transformations + + let chunks = read_sorted_arrays(r); + let unrestricted = r(); + //const read_chunked = () => new Set(read_sorted_array().flatMap(i => chunks[i]).concat(read_sorted_array())); + const read_chunked = () => { + // 20230921: build set in parts, 2x faster + let set = new Set(); + read_sorted_array().forEach(i => set_add_many(set, chunks[i])); + set_add_many(set, read_sorted_array()); + return set; + }; + GROUPS = read_array_while(i => { + // minifier property mangling seems unsafe + // so these are manually renamed to single chars + let N = read_array_while(r).map(x => x+0x60); + if (N.length) { + let R = i >= unrestricted; // unrestricted then restricted + N[0] -= 32; // capitalize + N = str_from_cps(N); + if (R) N=`Restricted[${N}]`; + let P = read_chunked(); // primary + let Q = read_chunked(); // secondary + let M = !r(); // not-whitelisted, check for NSM + // *** this code currently isn't needed *** + /* + let V = [...P, ...Q].sort((a, b) => a-b); // derive: sorted valid + let M = r()-1; // number of combining mark + if (M < 0) { // whitelisted + M = new Map(read_array_while(() => { + let i = r(); + if (i) return [V[i-1], read_array_while(() => { + let v = read_array_while(r); + if (v.length) return v.map(x => x-1); + })]; + })); + }*/ + return {N, P, Q, M, R}; + } + }); + + // decode compressed wholes + WHOLE_VALID = read_sorted_set(); + WHOLE_MAP = new Map(); + let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a, b) => a-b); // must be sorted + wholes.forEach((cp, i) => { + let d = r(); + let w = wholes[i] = d ? wholes[i-d] : {V: [], M: new Map()}; + w.V.push(cp); // add to member set + if (!WHOLE_VALID.has(cp)) { + WHOLE_MAP.set(cp, w); // register with whole map + } + }); + + // compute confusable-extent complements + // usage: WHOLE_MAP.get(cp).M.get(cp) = complement set + for (let {V, M} of new Set(WHOLE_MAP.values())) { + // connect all groups that have each whole character + let recs = []; + for (let cp of V) { + let gs = GROUPS.filter(g => group_has_cp(g, cp)); + let rec = recs.find(({G}) => gs.some(g => G.has(g))); + if (!rec) { + rec = {G: new Set(), V: []}; + recs.push(rec); + } + rec.V.push(cp); + set_add_many(rec.G, gs); + } + // per character cache groups which are not a member of the extent + let union = recs.flatMap(x => Array_from(x.G)); // all of the groups used by this whole + for (let {G, V} of recs) { + let complement = new Set(union.filter(g => !G.has(g))); // groups not covered by the extent + for (let cp of V) { + M.set(cp, complement); // this is the same reference + } + } + } + + // compute valid set + // 20230924: VALID was union but can be re-used + VALID = new Set(); // exists in 1+ groups + let multi = new Set(); // exists in 2+ groups + const add_to_union = cp => VALID.has(cp) ? multi.add(cp) : VALID.add(cp); + for (let g of GROUPS) { + for (let cp of g.P) add_to_union(cp); + for (let cp of g.Q) add_to_union(cp); + } + // dual purpose WHOLE_MAP: return placeholder if unique non-confusable + for (let cp of VALID) { + if (!WHOLE_MAP.has(cp) && !multi.has(cp)) { + WHOLE_MAP.set(cp, UNIQUE_PH); + } + } + // add all decomposed parts + // see derive: "Valid is Closed (via Brute-force)" + set_add_many(VALID, nfd(VALID)); + + // decode emoji + // 20230719: emoji are now fully-expanded to avoid quirk logic + EMOJI_LIST = read_trie(r).map(v => Emoji.from(v)).sort(compare_arrays); + EMOJI_ROOT = new Map(); // this has approx 7K nodes (2+ per emoji) + for (let cps of EMOJI_LIST) { + // 20230719: change to *slightly* stricter algorithm which disallows + // insertion of misplaced FE0F in emoji sequences (matching ENSIP-15) + // example: beautified [A B] (eg. flag emoji) + // before: allow: [A FE0F B], error: [A FE0F FE0F B] + // after: error: both + // note: this code now matches ENSNormalize.{cs,java} logic + let prev = [EMOJI_ROOT]; + for (let cp of cps) { + let next = prev.map(node => { + let child = node.get(cp); + if (!child) { + // should this be object? + // (most have 1-2 items, few have many) + // 20230719: no, v8 default map is 4? + child = new Map(); + node.set(cp, child); + } + return child; + }); + if (cp === FE0F) { + prev.push(...next); // less than 20 elements + } else { + prev = next; + } + } + for (let x of prev) { + x.V = cps; + } + } +} + +// if escaped: {HEX} +// else: "x" {HEX} +function quoted_cp(cp) { + return (should_escape(cp) ? '' : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp); +} + +// 20230211: some messages can be mixed-directional and result in spillover +// use 200E after a quoted string to force the remainder of a string from +// acquring the direction of the quote +// https://www.w3.org/International/questions/qa-bidi-unicode-controls#exceptions +function bidi_qq(s) { + return `"${s}"\u200E`; // strong LTR +} + +function check_label_extension(cps) { + if (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) { + throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); // this can only be ascii so cant be bidi + } +} +function check_leading_underscore(cps) { + const UNDERSCORE = 0x5F; + for (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) { + if (cps[--i] !== UNDERSCORE) { + throw new Error('underscore allowed only at start'); + } + } +} +// check that a fenced cp is not leading, trailing, or touching another fenced cp +function check_fenced(cps) { + let cp = cps[0]; + let prev = FENCED.get(cp); + if (prev) throw error_placement(`leading ${prev}`); + let n = cps.length; + let last = -1; // prevents trailing from throwing + for (let i = 1; i < n; i++) { + cp = cps[i]; + let match = FENCED.get(cp); + if (match) { + // since cps[0] isn't fenced, cps[1] cannot throw + if (last == i) throw error_placement(`${prev} + ${match}`); + last = i + 1; + prev = match; + } + } + if (last == n) throw error_placement(`trailing ${prev}`); +} + +// create a safe to print string +// invisibles are escaped +// leading cm uses placeholder +// if cps exceed max, middle truncate with ellipsis +// quoter(cp) => string, eg. 3000 => "{3000}" +// note: in html, you'd call this function then replace [<>&] with entities +function safe_str_from_cps(cps, max = Infinity, quoter = quote_cp) { + //if (Number.isInteger(cps)) cps = [cps]; + //if (!Array.isArray(cps)) throw new TypeError(`expected codepoints`); + let buf = []; + if (is_combining_mark(cps[0])) buf.push('◌'); + if (cps.length > max) { + max >>= 1; + cps = [...cps.slice(0, max), 0x2026, ...cps.slice(-max)]; + } + let prev = 0; + let n = cps.length; + for (let i = 0; i < n; i++) { + let cp = cps[i]; + if (should_escape(cp)) { + buf.push(str_from_cps(cps.slice(prev, i))); + buf.push(quoter(cp)); + prev = i + 1; + } + } + buf.push(str_from_cps(cps.slice(prev, n))); + return buf.join(''); +} + +// note: set(s) cannot be exposed because they can be modified +// note: Object.freeze() doesn't work +function is_combining_mark(cp) { + init(); + return CM.has(cp); +} +function should_escape(cp) { + init(); + return ESCAPE.has(cp); +} + +// return all supported emoji as fully-qualified emoji +// ordered by length then lexicographic +function ens_emoji() { + init(); + return EMOJI_LIST.map(x => x.slice()); // emoji are exposed so copy +} + +function ens_normalize_fragment(frag, decompose) { + init(); + let nf = decompose ? nfd : nfc; + return frag.split(STOP_CH).map(label => str_from_cps(tokens_from_str(explode_cp(label), nf, filter_fe0f).flat())).join(STOP_CH); +} + +function ens_normalize(name) { + return flatten(split(name, nfc, filter_fe0f)); +} + +function ens_beautify(name) { + let labels = split(name, nfc, x => x); // emoji not exposed + for (let {type, output, error} of labels) { + if (error) break; // flatten will throw + + // replace leading/trailing hyphen + // 20230121: consider beautifing all or leading/trailing hyphen to unicode variant + // not exactly the same in every font, but very similar: "-" vs "‐" + /* + const UNICODE_HYPHEN = 0x2010; + // maybe this should replace all for visual consistancy? + // `node tools/reg-count.js regex ^-\{2,\}` => 592 + //for (let i = 0; i < output.length; i++) if (output[i] == 0x2D) output[i] = 0x2010; + if (output[0] == HYPHEN) output[0] = UNICODE_HYPHEN; + let end = output.length-1; + if (output[end] == HYPHEN) output[end] = UNICODE_HYPHEN; + */ + // 20230123: WHATWG URL uses "CheckHyphens" false + // https://url.spec.whatwg.org/#idna + + // update ethereum symbol + // ξ => Ξ if not greek + if (type !== 'Greek') array_replace(output, 0x3BE, 0x39E); + + // 20221213: fixes bidi subdomain issue, but breaks invariant (200E is disallowed) + // could be fixed with special case for: 2D (.) + 200E (LTR) + // https://discuss.ens.domains/t/bidi-label-ordering-spoof/15824 + //output.splice(0, 0, 0x200E); + } + return flatten(labels); +} + +function array_replace(v, a, b) { + let prev = 0; + while (true) { + let next = v.indexOf(a, prev); + if (next < 0) break; + v[next] = b; + prev = next + 1; + } +} + +function ens_split(name, preserve_emoji) { + return split(name, nfc, preserve_emoji ? x => x.slice() : filter_fe0f); // emoji are exposed so copy +} + +function split(name, nf, ef) { + if (!name) return []; // 20230719: empty name allowance + init(); + let offset = 0; + // https://unicode.org/reports/tr46/#Validity_Criteria + // 4.) "The label must not contain a U+002E ( . ) FULL STOP." + return name.split(STOP_CH).map(label => { + let input = explode_cp(label); + let info = { + input, + offset, // codepoint, not substring! + }; + offset += input.length + 1; // + stop + try { + // 1.) "The label must be in Unicode Normalization Form NFC" + let tokens = info.tokens = tokens_from_str(input, nf, ef); + let token_count = tokens.length; + let type; + if (!token_count) { // the label was effectively empty (could of had ignored characters) + //norm = []; + //type = 'None'; // use this instead of next match, "ASCII" + // 20230120: change to strict + // https://discuss.ens.domains/t/ens-name-normalization-2nd/14564/59 + throw new Error(`empty label`); + } + let norm = info.output = tokens.flat(); + check_leading_underscore(norm); + let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; // same as: tokens.some(x => x.is_emoji); + if (!emoji && norm.every(cp => cp < 0x80)) { // special case for ascii + // 20230123: matches matches WHATWG, see note 3.3 + check_label_extension(norm); // only needed for ascii + // cant have fenced + // cant have cm + // cant have wholes + // see derive: "Fastpath ASCII" + type = 'ASCII'; + } else { + let chars = tokens.flatMap(x => x.is_emoji ? [] : x); // all of the nfc tokens concat together + if (!chars.length) { // theres no text, just emoji + type = 'Emoji'; + } else { + // 5.) "The label must not begin with a combining mark, that is: General_Category=Mark." + if (CM.has(norm[0])) throw error_placement('leading combining mark'); + for (let i = 1; i < token_count; i++) { // we've already checked the first token + let cps = tokens[i]; + if (!cps.is_emoji && CM.has(cps[0])) { // every text token has emoji neighbors, eg. EtEEEtEt... + // bidi_qq() not needed since emoji is LTR and cps is a CM + throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i-1])} + ${safe_str_from_cps([cps[0]])}"`); + } + } + check_fenced(norm); + let unique = Array_from(new Set(chars)); + let [g] = determine_group(unique); // take the first match + // see derive: "Matching Groups have Same CM Style" + // alternative: could form a hybrid type: Latin/Japanese/... + check_group(g, chars); // need text in order + check_whole(g, unique); // only need unique text (order would be required for multiple-char confusables) + type = g.N; + // 20230121: consider exposing restricted flag + // it's simpler to just check for 'Restricted' + // or even better: type.endsWith(']') + //if (g.R) info.restricted = true; + } + } + info.type = type; + } catch (err) { + info.error = err; // use full error object + } + return info; + }); +} + +function check_whole(group, unique) { + let maker; + let shared = []; + for (let cp of unique) { + let whole = WHOLE_MAP.get(cp); + if (whole === UNIQUE_PH) return; // unique, non-confusable + if (whole) { + let set = whole.M.get(cp); // groups which have a character that look-like this character + maker = maker ? maker.filter(g => set.has(g)) : Array_from(set); + if (!maker.length) return; // confusable intersection is empty + } else { + shared.push(cp); + } + } + if (maker) { + // we have 1+ confusable + // check if any of the remaining groups + // contain the shared characters too + for (let g of maker) { + if (shared.every(cp => group_has_cp(g, cp))) { + throw new Error(`whole-script confusable: ${group.N}/${g.N}`); + } + } + } +} + +// assumption: unique.size > 0 +// returns list of matching groups +function determine_group(unique) { + let groups = GROUPS; + for (let cp of unique) { + // note: we need to dodge CM that are whitelisted + // but that code isn't currently necessary + let gs = groups.filter(g => group_has_cp(g, cp)); + if (!gs.length) { + if (!GROUPS.some(g => group_has_cp(g, cp))) { + // the character was composed of valid parts + // but it's NFC form is invalid + // 20230716: change to more exact statement, see: ENSNormalize.{cs,java} + // note: this doesn't have to be a composition + // 20230720: change to full check + throw error_disallowed(cp); // this should be rare + } else { + // there is no group that contains all these characters + // throw using the highest priority group that matched + // https://www.unicode.org/reports/tr39/#mixed_script_confusables + throw error_group_member(groups[0], cp); + } + } + groups = gs; + if (gs.length == 1) break; // there is only one group left + } + // there are at least 1 group(s) with all of these characters + return groups; +} + +// throw on first error +function flatten(split) { + return split.map(({input, error, output}) => { + if (error) { + // don't print label again if just a single label + let msg = error.message; + // bidi_qq() only necessary if msg is digits + throw new Error(split.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input, 63))}: ${msg}`); + } + return str_from_cps(output); + }).join(STOP_CH); +} + +function error_disallowed(cp) { + // TODO: add cp to error? + return new Error(`disallowed character: ${quoted_cp(cp)}`); +} +function error_group_member(g, cp) { + let quoted = quoted_cp(cp); + let gg = GROUPS.find(g => g.P.has(cp)); // only check primary + if (gg) { + quoted = `${gg.N} ${quoted}`; + } + return new Error(`illegal mixture: ${g.N} + ${quoted}`); +} +function error_placement(where) { + return new Error(`illegal placement: ${where}`); +} + +// assumption: cps.length > 0 +// assumption: cps[0] isn't a CM +// assumption: the previous character isn't an emoji +function check_group(g, cps) { + for (let cp of cps) { + if (!group_has_cp(g, cp)) { + // for whitelisted scripts, this will throw illegal mixture on invalid cm, eg. "e{300}{300}" + // at the moment, it's unnecessary to introduce an extra error type + // until there exists a whitelisted multi-character + // eg. if (M < 0 && is_combining_mark(cp)) { ... } + // there are 3 cases: + // 1. illegal cm for wrong group => mixture error + // 2. illegal cm for same group => cm error + // requires set of whitelist cm per group: + // eg. new Set([...g.P, ...g.Q].flatMap(nfc).filter(cp => CM.has(cp))) + // 3. wrong group => mixture error + throw error_group_member(g, cp); + } + } + //if (M >= 0) { // we have a known fixed cm count + if (g.M) { // we need to check for NSM + let decomposed = nfd(cps); + for (let i = 1, e = decomposed.length; i < e; i++) { // see: assumption + // 20230210: bugfix: using cps instead of decomposed h/t Carbon225 + /* + if (CM.has(decomposed[i])) { + let j = i + 1; + while (j < e && CM.has(decomposed[j])) j++; + if (j - i > M) { + throw new Error(`too many combining marks: ${g.N} ${bidi_qq(str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${M})`); + } + i = j; + } + */ + // 20230217: switch to NSM counting + // https://www.unicode.org/reports/tr39/#Optional_Detection + if (NSM.has(decomposed[i])) { + let j = i + 1; + for (let cp; j < e && NSM.has(cp = decomposed[j]); j++) { + // a. Forbid sequences of the same nonspacing mark. + for (let k = i; k < j; k++) { // O(n^2) but n < 100 + if (decomposed[k] == cp) { + throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`); + } + } + } + // parse to end so we have full nsm count + // b. Forbid sequences of more than 4 nonspacing marks (gc=Mn or gc=Me). + if (j - i > NSM_MAX) { + // note: this slice starts with a base char or spacing-mark cm + throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${NSM_MAX})`); + } + i = j; + } + } + } + // *** this code currently isn't needed *** + /* + let cm_whitelist = M instanceof Map; + for (let i = 0, e = cps.length; i < e; ) { + let cp = cps[i++]; + let seqs = cm_whitelist && M.get(cp); + if (seqs) { + // list of codepoints that can follow + // if this exists, this will always be 1+ + let j = i; + while (j < e && CM.has(cps[j])) j++; + let cms = cps.slice(i, j); + let match = seqs.find(seq => !compare_arrays(seq, cms)); + if (!match) throw new Error(`disallowed combining mark sequence: "${safe_str_from_cps([cp, ...cms])}"`); + i = j; + } else if (!V.has(cp)) { + // https://www.unicode.org/reports/tr39/#mixed_script_confusables + let quoted = quoted_cp(cp); + for (let cp of cps) { + let u = UNIQUE.get(cp); + if (u && u !== g) { + // if both scripts are restricted this error is confusing + // because we don't differentiate RestrictedA from RestrictedB + if (!u.R) quoted = `${quoted} is ${u.N}`; + break; + } + } + throw new Error(`disallowed ${g.N} character: ${quoted}`); + //throw new Error(`disallowed character: ${quoted} (expected ${g.N})`); + //throw new Error(`${g.N} does not allow: ${quoted}`); + } + } + if (!cm_whitelist) { + let decomposed = nfd(cps); + for (let i = 1, e = decomposed.length; i < e; i++) { // we know it can't be cm leading + if (CM.has(decomposed[i])) { + let j = i + 1; + while (j < e && CM.has(decomposed[j])) j++; + if (j - i > M) { + throw new Error(`too many combining marks: "${str_from_cps(decomposed.slice(i-1, j))}" (${j-i}/${M})`); + } + i = j; + } + } + } + */ +} + +// given a list of codepoints +// returns a list of lists, where emoji are a fully-qualified (as Array subclass) +// eg. explode_cp("abc💩d") => [[61, 62, 63], Emoji[1F4A9, FE0F], [64]] +// 20230818: rename for 'process' name collision h/t Javarome +// https://github.com/adraffy/ens-normalize.js/issues/23 +function tokens_from_str(input, nf, ef) { + let ret = []; + let chars = []; + input = input.slice().reverse(); // flip so we can pop + while (input.length) { + let emoji = consume_emoji_reversed(input); + if (emoji) { + if (chars.length) { + ret.push(nf(chars)); + chars = []; + } + ret.push(ef(emoji)); + } else { + let cp = input.pop(); + if (VALID.has(cp)) { + chars.push(cp); + } else { + let cps = MAPPED.get(cp); + if (cps) { + chars.push(...cps); // less than 10 elements + } else if (!IGNORED.has(cp)) { + // 20230912: unicode 15.1 changed the order of processing such that + // disallowed parts are only rejected after NFC + // https://unicode.org/reports/tr46/#Validity_Criteria + // this doesn't impact normalization as of today + // technically, this error can be removed as the group logic will apply similar logic + // however the error type might be less clear + throw error_disallowed(cp); + } + } + } + } + if (chars.length) { + ret.push(nf(chars)); + } + return ret; +} + +function filter_fe0f(cps) { + return cps.filter(cp => cp != FE0F); +} + +// given array of codepoints +// returns the longest valid emoji sequence (or undefined if no match) +// *MUTATES* the supplied array +// disallows interleaved ignored characters +// fills (optional) eaten array with matched codepoints +function consume_emoji_reversed(cps, eaten) { + let node = EMOJI_ROOT; + let emoji; + let pos = cps.length; + while (pos) { + node = node.get(cps[--pos]); + if (!node) break; + let {V} = node; + if (V) { // this is a valid emoji (so far) + emoji = V; + if (eaten) eaten.push(...cps.slice(pos).reverse()); // (optional) copy input, used for ens_tokenize() + cps.length = pos; // truncate + } + } + return emoji; +} + +// ************************************************************ +// tokenizer + +const TY_VALID = 'valid'; +const TY_MAPPED = 'mapped'; +const TY_IGNORED = 'ignored'; +const TY_DISALLOWED = 'disallowed'; +const TY_EMOJI = 'emoji'; +const TY_NFC = 'nfc'; +const TY_STOP = 'stop'; + +function ens_tokenize(name, { + nf = true, // collapse unnormalized runs into a single token +} = {}) { + init(); + let input = explode_cp(name).reverse(); + let eaten = []; + let tokens = []; + while (input.length) { + let emoji = consume_emoji_reversed(input, eaten); + if (emoji) { + tokens.push({ + type: TY_EMOJI, + emoji: emoji.slice(), // copy emoji + input: eaten, + cps: filter_fe0f(emoji) + }); + eaten = []; // reset buffer + } else { + let cp = input.pop(); + if (cp == STOP) { + tokens.push({type: TY_STOP, cp}); + } else if (VALID.has(cp)) { + tokens.push({type: TY_VALID, cps: [cp]}); + } else if (IGNORED.has(cp)) { + tokens.push({type: TY_IGNORED, cp}); + } else { + let cps = MAPPED.get(cp); + if (cps) { + tokens.push({type: TY_MAPPED, cp, cps: cps.slice()}); + } else { + tokens.push({type: TY_DISALLOWED, cp}); + } + } + } + } + if (nf) { + for (let i = 0, start = -1; i < tokens.length; i++) { + let token = tokens[i]; + if (is_valid_or_mapped(token.type)) { + if (requires_check(token.cps)) { // normalization might be needed + let end = i + 1; + for (let pos = end; pos < tokens.length; pos++) { // find adjacent text + let {type, cps} = tokens[pos]; + if (is_valid_or_mapped(type)) { + if (!requires_check(cps)) break; + end = pos + 1; + } else if (type !== TY_IGNORED) { // || type !== TY_DISALLOWED) { + break; + } + } + if (start < 0) start = i; + let slice = tokens.slice(start, end); + let cps0 = slice.flatMap(x => is_valid_or_mapped(x.type) ? x.cps : []); // strip junk tokens + let cps = nfc(cps0); + if (compare_arrays(cps, cps0)) { // bundle into an nfc token + tokens.splice(start, end - start, { + type: TY_NFC, + input: cps0, // there are 3 states: tokens0 ==(process)=> input ==(nfc)=> tokens/cps + cps, + tokens0: collapse_valid_tokens(slice), + tokens: ens_tokenize(str_from_cps(cps), {nf: false}) + }); + i = start; + } else { + i = end - 1; // skip to end of slice + } + start = -1; // reset + } else { + start = i; // remember last + } + } else if (token.type !== TY_IGNORED) { // 20221024: is this correct? + start = -1; // reset + } + } + } + return collapse_valid_tokens(tokens); +} + +function is_valid_or_mapped(type) { + return type == TY_VALID || type == TY_MAPPED; +} + +function requires_check(cps) { + return cps.some(cp => NFC_CHECK.has(cp)); +} + +function collapse_valid_tokens(tokens) { + for (let i = 0; i < tokens.length; i++) { + if (tokens[i].type == TY_VALID) { + let j = i + 1; + while (j < tokens.length && tokens[j].type == TY_VALID) j++; + tokens.splice(i, j - i, {type: TY_VALID, cps: tokens.slice(i, j).flatMap(x => x.cps)}); + } + } + return tokens; +} + + + +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/hash/namehash.js + + + +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + (0,errors/* assertArgument */.MR)(comp.length !== 0, "invalid ENS name; empty component", "comp", comp); + return comp; +} +function ensNameSplit(name) { + const bytes = (0,utf8/* toUtf8Bytes */.YW)(ensNormalize(name)); + const comps = []; + if (name.length === 0) { + return comps; + } + let last = 0; + for (let i = 0; i < bytes.length; i++) { + const d = bytes[i]; + // A separator (i.e. "."); copy this component + if (d === 0x2e) { + comps.push(checkComponent(bytes.slice(last, i))); + last = i + 1; + } + } + // There was a stray separator at the end of the name + (0,errors/* assertArgument */.MR)(last < bytes.length, "invalid ENS name; empty component", "name", name); + comps.push(checkComponent(bytes.slice(last))); + return comps; +} +/** + * Returns the ENS %%name%% normalized. + */ +function ensNormalize(name) { + try { + if (name.length === 0) { + throw new Error("empty label"); + } + return ens_normalize(name); + } + catch (error) { + (0,errors/* assertArgument */.MR)(false, `invalid ENS name (${error.message})`, "name", name); + } +} +/** + * Returns ``true`` if %%name%% is a valid ENS name. + */ +function isValidName(name) { + try { + return (ensNameSplit(name).length !== 0); + } + catch (error) { } + return false; +} +/** + * Returns the [[link-namehash]] for %%name%%. + */ +function namehash(name) { + (0,errors/* assertArgument */.MR)(typeof (name) === "string", "invalid ENS name; not a string", "name", name); + (0,errors/* assertArgument */.MR)(name.length, `invalid ENS name (empty label)`, "name", name); + let result = Zeros; + const comps = ensNameSplit(name); + while (comps.length) { + result = (0,keccak/* keccak256 */.S)((0,data/* concat */.xW)([result, (0,keccak/* keccak256 */.S)((comps.pop()))])); + } + return (0,data/* hexlify */.c$)(result); +} +/** + * Returns the DNS encoded %%name%%. + * + * This is used for various parts of ENS name resolution, such + * as the wildcard resolution. + */ +function dnsEncode(name, _maxLength) { + const length = (_maxLength != null) ? _maxLength : 63; + (0,errors/* assertArgument */.MR)(length <= 255, "DNS encoded label cannot exceed 255", "length", length); + return (0,data/* hexlify */.c$)((0,data/* concat */.xW)(ensNameSplit(name).map((comp) => { + (0,errors/* assertArgument */.MR)(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, "name", name); + const bytes = new Uint8Array(comp.length + 1); + bytes.set(comp, 1); + bytes[0] = bytes.length - 1; + return bytes; + }))) + "00"; +} +//# sourceMappingURL=namehash.js.map + +/***/ }), + +/***/ 43948: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ J9: () => (/* binding */ FeeData), +/* harmony export */ VS: () => (/* binding */ copyRequest), +/* harmony export */ eB: () => (/* binding */ Block), +/* harmony export */ tG: () => (/* binding */ Log), +/* harmony export */ uI: () => (/* binding */ TransactionResponse), +/* harmony export */ z5: () => (/* binding */ TransactionReceipt) +/* harmony export */ }); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88081); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36212); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27033); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57339); +/* harmony import */ var _transaction_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8177); +//import { resolveAddress } from "@ethersproject/address"; + + +const BN_0 = BigInt(0); +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +/** + * A **FeeData** wraps all the fee-related values associated with + * the network. + */ +class FeeData { + /** + * The gas price for legacy networks. + */ + gasPrice; + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxFeePerGas; + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxPriorityFeePerGas; + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +; +/** + * Returns a copy of %%req%% with all properties coerced to their strict + * types. + */ +function copyRequest(req) { + const result = {}; + // These could be addresses, ENS names or Addressables + if (req.to) { + result.to = req.to; + } + if (req.from) { + result.from = req.from; + } + if (req.data) { + result.data = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)(req.data); + } + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); + for (const key of bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBigInt */ .Ab)(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key of numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getNumber */ .WZ)(req[key], `request.${key}`); + } + if (req.accessList) { + result.accessList = (0,_transaction_index_js__WEBPACK_IMPORTED_MODULE_3__/* .accessListify */ .$)(req.accessList); + } + if ("blockTag" in req) { + result.blockTag = req.blockTag; + } + if ("enableCcipRead" in req) { + result.enableCcipRead = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + if ("blobVersionedHashes" in req && req.blobVersionedHashes) { + result.blobVersionedHashes = req.blobVersionedHashes.slice(); + } + if ("kzg" in req) { + result.kzg = req.kzg; + } + if ("blobs" in req && req.blobs) { + result.blobs = req.blobs.map((b) => { + if ((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .isBytesLike */ .f)(b)) { + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)(b); + } + return Object.assign({}, b); + }); + } + return result; +} +/** + * A **Block** represents the data associated with a full block on + * Ethereum. + */ +class Block { + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + provider; + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + number; + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + hash; + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + timestamp; + /** + * The block hash of the parent block. + */ + parentHash; + /** + * The hash tree root of the parent beacon block for the given + * execution block. See [[link-eip-4788]]. + */ + parentBeaconBlockRoot; + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + nonce; + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + difficulty; + /** + * The total gas limit for this block. + */ + gasLimit; + /** + * The total gas used in this block. + */ + gasUsed; + /** + * The root hash for the global state after applying changes + * in this block. + */ + stateRoot; + /** + * The hash of the transaction receipts trie. + */ + receiptsRoot; + /** + * The total amount of blob gas consumed by the transactions + * within the block. See [[link-eip-4844]]. + */ + blobGasUsed; + /** + * The running total of blob gas consumed in excess of the + * target, prior to the block. See [[link-eip-4844]]. + */ + excessBlobGas; + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + miner; + /** + * The latest RANDAO mix of the post beacon state of + * the previous block. + */ + prevRandao; + /** + * Any extra data the validator wished to include. + */ + extraData; + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + baseFeePerGas; + #transactions; + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block, provider) { + this.#transactions = block.transactions.map((tx) => { + if (typeof (tx) !== "string") { + return new TransactionResponse(tx, provider); + } + return tx; + }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + provider, + hash: getValue(block.hash), + number: block.number, + timestamp: block.timestamp, + parentHash: block.parentHash, + parentBeaconBlockRoot: block.parentBeaconBlockRoot, + nonce: block.nonce, + difficulty: block.difficulty, + gasLimit: block.gasLimit, + gasUsed: block.gasUsed, + blobGasUsed: block.blobGasUsed, + excessBlobGas: block.excessBlobGas, + miner: block.miner, + prevRandao: getValue(block.prevRandao), + extraData: block.extraData, + baseFeePerGas: getValue(block.baseFeePerGas), + stateRoot: block.stateRoot, + receiptsRoot: block.receiptsRoot, + }); + } + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions() { + return this.#transactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return tx.hash; + }); + } + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions() { + const txs = this.#transactions.slice(); + // Doesn't matter... + if (txs.length === 0) { + return []; + } + // Make sure we prefetched the transactions + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + blobGasUsed: toJson(this.blobGasUsed), + excessBlobGas: toJson(this.excessBlobGas), + hash, miner, prevRandao, nonce, number, parentHash, timestamp, + parentBeaconBlockRoot, stateRoot, receiptsRoot, + transactions, + }; + } + [Symbol.iterator]() { + let index = 0; + const txs = this.transactions; + return { + next: () => { + if (index < this.length) { + return { + value: txs[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The number of transactions in this block. + */ + get length() { return this.#transactions.length; } + /** + * The [[link-js-date]] this block was included at. + */ + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + /** + * Get the transaction at %%indexe%% within this block. + */ + async getTransaction(indexOrHash) { + // Find the internal value by its index or hash + let tx = undefined; + if (typeof (indexOrHash) === "number") { + tx = this.#transactions[indexOrHash]; + } + else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#transactions) { + if (typeof (v) === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } + else { + if (v.hash === hash) { + continue; + } + tx = v; + break; + } + } + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash) { + const txs = this.prefetchedTransactions; + if (typeof (indexOrHash) === "number") { + return txs[indexOrHash]; + } + indexOrHash = indexOrHash.toLowerCase(); + for (const tx of txs) { + if (tx.hash === indexOrHash) { + return tx; + } + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assertArgument */ .MR)(false, "no matching transaction", "indexOrHash", indexOrHash); + } + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined() { return !!this.hash; } + /** + * Returns true if this block is an [[link-eip-2930]] block. + */ + isLondon() { + return !!this.baseFeePerGas; + } + /** + * @_ignore: + */ + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +////////////////////// +// Log +/** + * A **Log** in Ethereum represents an event that has been included in a + * transaction using the ``LOG*`` opcodes, which are most commonly used by + * Solidity's emit for announcing events. + */ +class Log { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + transactionHash; + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + blockHash; + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + blockNumber; + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + removed; + /** + * The address of the contract that emitted this log. + */ + address; + /** + * The data included in this log when it was emitted. + */ + data; + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + topics; + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + index; + /** + * The index within the transaction of this log. + */ + transactionIndex; + /** + * @_ignore: + */ + constructor(log, provider) { + this.provider = provider; + const topics = Object.freeze(log.topics.slice()); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + removed: log.removed, + address: log.address, + data: log.data, + topics, + index: log.index, + transactionIndex: log.transactionIndex, + }); + } + /** + * Returns a JSON-compatible object. + */ + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + /** + * Returns the block that this log occurred in. + */ + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); + return block; + } + /** + * Returns the transaction that this log occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.transactionHash); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); + return tx; + } + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + async getTransactionReceipt() { + const receipt = await this.provider.getTransactionReceipt(this.transactionHash); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); + return receipt; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedLogFilter(this); + } +} +////////////////////// +// Transaction Receipt +/* +export interface LegacyTransactionReceipt { + byzantium: false; + status: null; + root: string; +} + +export interface ByzantiumTransactionReceipt { + byzantium: true; + status: number; + root: null; +} +*/ +/** + * A **TransactionReceipt** includes additional information about a + * transaction that is only available after it has been mined. + */ +class TransactionReceipt { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The address the transaction was sent to. + */ + to; + /** + * The sender of the transaction. + */ + from; + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + contractAddress; + /** + * The transaction hash. + */ + hash; + /** + * The index of this transaction within the block transactions. + */ + index; + /** + * The block hash of the [[Block]] this transaction was included in. + */ + blockHash; + /** + * The block number of the [[Block]] this transaction was included in. + */ + blockNumber; + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + logsBloom; + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + gasUsed; + /** + * The gas used for BLObs. See [[link-eip-4844]]. + */ + blobGasUsed; + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + cumulativeGasUsed; + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + gasPrice; + /** + * The price paid per BLOB in gas. See [[link-eip-4844]]. + */ + blobGasPrice; + /** + * The [[link-eip-2718]] transaction type. + */ + type; + //readonly byzantium!: boolean; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + status; + /** + * The root hash of this transaction. + * + * This is no present and was only included in pre-byzantium blocks, but + * could be used to validate certain parts of the receipt. + */ + root; + #logs; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.#logs = Object.freeze(tx.logs.map((log) => { + return new Log(log, provider); + })); + let gasPrice = BN_0; + if (tx.effectiveGasPrice != null) { + gasPrice = tx.effectiveGasPrice; + } + else if (tx.gasPrice != null) { + gasPrice = tx.gasPrice; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { + provider, + to: tx.to, + from: tx.from, + contractAddress: tx.contractAddress, + hash: tx.hash, + index: tx.index, + blockHash: tx.blockHash, + blockNumber: tx.blockNumber, + logsBloom: tx.logsBloom, + gasUsed: tx.gasUsed, + cumulativeGasUsed: tx.cumulativeGasUsed, + blobGasUsed: tx.blobGasUsed, + gasPrice, + blobGasPrice: tx.blobGasPrice, + type: tx.type, + //byzantium: tx.byzantium, + status: tx.status, + root: tx.root + }); + } + /** + * The logs for this transaction. + */ + get logs() { return this.#logs; } + /** + * Returns a JSON-compatible representation. + */ + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, + status, root } = this; + return { + _type: "TransactionReceipt", + blockHash, blockNumber, + //byzantium, + contractAddress, + cumulativeGasUsed: toJson(this.cumulativeGasUsed), + from, + gasPrice: toJson(this.gasPrice), + blobGasUsed: toJson(this.blobGasUsed), + blobGasPrice: toJson(this.blobGasPrice), + gasUsed: toJson(this.gasUsed), + hash, index, logs, logsBloom, root, status, to + }; + } + /** + * @_ignore: + */ + get length() { return this.logs.length; } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { value: this.logs[index++], done: false }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The total fee for this transaction, in wei. + */ + get fee() { + return this.gasUsed * this.gasPrice; + } + /** + * Resolves to the block this transaction occurred in. + */ + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to the transaction this transaction occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + async getResult() { + return (await this.provider.getTransactionResult(this.hash)); + } + /** + * Resolves to the number of confirmations this transaction has. + */ + async confirmations() { + return (await this.provider.getBlockNumber()) - this.blockNumber + 1; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedTransactionFilter(this); + } + /** + * @_ignore: + */ + reorderedEvent(other) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }); + return createReorderedTransactionFilter(this, other); + } +} +/** + * A **TransactionResponse** includes all properties about a transaction + * that was sent to the network, which may or may not be included in a + * block. + * + * The [[TransactionResponse-isMined]] can be used to check if the + * transaction has been mined as well as type guard that the otherwise + * possibly ``null`` properties are defined. + */ +class TransactionResponse { + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + provider; + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockNumber; + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockHash; + /** + * The index within the block that this transaction resides at. + */ + index; + /** + * The transaction hash. + */ + hash; + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + type; + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + to; + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + from; + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + nonce; + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + gasLimit; + /** + * The gas price can have various values, depending on the network. + * + * In modern networks, for transactions that are included this is + * the //effective gas price// (the fee per gas that was actually + * charged), while for transactions that have not been included yet + * is the [[maxFeePerGas]]. + * + * For legacy transactions, or transactions on legacy networks, this + * is the fee that will be charged per unit of gas the transaction + * consumes. + */ + gasPrice; + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + maxPriorityFeePerGas; + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + maxFeePerGas; + /** + * The [[link-eip-4844]] max fee per BLOb gas. + */ + maxFeePerBlobGas; + /** + * The data. + */ + data; + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + value; + /** + * The chain ID. + */ + chainId; + /** + * The signature. + */ + signature; + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + accessList; + /** + * The [[link-eip-4844]] BLOb versioned hashes. + */ + blobVersionedHashes; + #startBlock; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.provider = provider; + this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null; + this.blockHash = (tx.blockHash != null) ? tx.blockHash : null; + this.hash = tx.hash; + this.index = tx.index; + this.type = tx.type; + this.from = tx.from; + this.to = tx.to || null; + this.gasLimit = tx.gasLimit; + this.nonce = tx.nonce; + this.data = tx.data; + this.value = tx.value; + this.gasPrice = tx.gasPrice; + this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null; + this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null; + this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas : null; + this.chainId = tx.chainId; + this.signature = tx.signature; + this.accessList = (tx.accessList != null) ? tx.accessList : null; + this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes : null; + this.#startBlock = -1; + } + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this; + return { + _type: "TransactionResponse", + accessList, blockNumber, blockHash, + blobVersionedHashes, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + maxFeePerBlobGas: toJson(this.maxFeePerBlobGas), + nonce, signature, to, index, type, + value: toJson(this.value), + }; + } + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + async getBlock() { + let blockNumber = this.blockNumber; + if (blockNumber == null) { + const tx = await this.getTransaction(); + if (tx) { + blockNumber = tx.blockNumber; + } + } + if (blockNumber == null) { + return null; + } + const block = this.provider.getBlock(blockNumber); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + /** + * Resolve to the number of confirmations this transaction has. + */ + async confirmations() { + if (this.blockNumber == null) { + const { tx, blockNumber } = await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .resolveProperties */ .k)({ + tx: this.getTransaction(), + blockNumber: this.provider.getBlockNumber() + }); + // Not mined yet... + if (tx == null || tx.blockNumber == null) { + return 0; + } + return blockNumber - tx.blockNumber + 1; + } + const blockNumber = await this.provider.getBlockNumber(); + return blockNumber - this.blockNumber + 1; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(_confirms, _timeout) { + const confirms = (_confirms == null) ? 1 : _confirms; + const timeout = (_timeout == null) ? 0 : _timeout; + let startBlock = this.#startBlock; + let nextScan = -1; + let stopScanning = (startBlock === -1) ? true : false; + const checkReplacement = async () => { + // Get the current transaction count for this sender + if (stopScanning) { + return null; + } + const { blockNumber, nonce } = await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .resolveProperties */ .k)({ + blockNumber: this.provider.getBlockNumber(), + nonce: this.provider.getTransactionCount(this.from) + }); + // No transaction or our nonce has not been mined yet; but we + // can start scanning later when we do start + if (nonce < this.nonce) { + startBlock = blockNumber; + return; + } + // We were mined; no replacement + if (stopScanning) { + return null; + } + const mined = await this.getTransaction(); + if (mined && mined.blockNumber != null) { + return; + } + // We were replaced; start scanning for that transaction + // Starting to scan; look back a few extra blocks for safety + if (nextScan === -1) { + nextScan = startBlock - 3; + if (nextScan < this.#startBlock) { + nextScan = this.#startBlock; + } + } + while (nextScan <= blockNumber) { + // Get the next block to scan + if (stopScanning) { + return null; + } + const block = await this.provider.getBlock(nextScan, true); + // This should not happen; but we'll try again shortly + if (block == null) { + return; + } + // We were mined; no replacement + for (const hash of block) { + if (hash === this.hash) { + return; + } + } + // Search for the transaction that replaced us + for (let i = 0; i < block.length; i++) { + const tx = await block.getTransaction(i); + if (tx.from === this.from && tx.nonce === this.nonce) { + // Get the receipt + if (stopScanning) { + return null; + } + const receipt = await this.provider.getTransactionReceipt(tx.hash); + // This should not happen; but we'll try again shortly + if (receipt == null) { + return; + } + // We will retry this on the next block (this case could be optimized) + if ((blockNumber - receipt.blockNumber + 1) < confirms) { + return; + } + // The reason we were replaced + let reason = "replaced"; + if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { + reason = "repriced"; + } + else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0) { + reason = "cancelled"; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(false, "transaction was replaced", "TRANSACTION_REPLACED", { + cancelled: (reason === "replaced" || reason === "cancelled"), + reason, + replacement: tx.replaceableTransaction(startBlock), + hash: tx.hash, + receipt + }); + } + } + nextScan++; + } + return; + }; + const checkReceipt = (receipt) => { + if (receipt == null || receipt.status !== 0) { + return receipt; + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(false, "transaction execution reverted", "CALL_EXCEPTION", { + action: "sendTransaction", + data: null, reason: null, invocation: null, revert: null, + transaction: { + to: receipt.to, + from: receipt.from, + data: "" // @TODO: in v7, split out sendTransaction properties + }, receipt + }); + }; + const receipt = await this.provider.getTransactionReceipt(this.hash); + if (confirms === 0) { + return checkReceipt(receipt); + } + if (receipt) { + if ((await receipt.confirmations()) >= confirms) { + return checkReceipt(receipt); + } + } + else { + // Check for a replacement; throws if a replacement was found + await checkReplacement(); + // Allow null only when the confirms is 0 + if (confirms === 0) { + return null; + } + } + const waiter = new Promise((resolve, reject) => { + // List of things to cancel when we have a result (one way or the other) + const cancellers = []; + const cancel = () => { cancellers.forEach((c) => c()); }; + // On cancel, stop scanning for replacements + cancellers.push(() => { stopScanning = true; }); + // Set up any timeout requested + if (timeout > 0) { + const timer = setTimeout(() => { + cancel(); + reject((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .makeError */ .xz)("wait for transaction timeout", "TIMEOUT")); + }, timeout); + cancellers.push(() => { clearTimeout(timer); }); + } + const txListener = async (receipt) => { + // Done; return it! + if ((await receipt.confirmations()) >= confirms) { + cancel(); + try { + resolve(checkReceipt(receipt)); + } + catch (error) { + reject(error); + } + } + }; + cancellers.push(() => { this.provider.off(this.hash, txListener); }); + this.provider.on(this.hash, txListener); + // We support replacement detection; start checking + if (startBlock >= 0) { + const replaceListener = async () => { + try { + // Check for a replacement; this throws only if one is found + await checkReplacement(); + } + catch (error) { + // We were replaced (with enough confirms); re-throw the error + if ((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .isError */ .bJ)(error, "TRANSACTION_REPLACED")) { + cancel(); + reject(error); + return; + } + } + // Rescheudle a check on the next block + if (!stopScanning) { + this.provider.once("block", replaceListener); + } + }; + cancellers.push(() => { this.provider.off("block", replaceListener); }); + this.provider.once("block", replaceListener); + } + }); + return await waiter; + } + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined() { + return (this.blockHash != null); + } + /** + * Returns true if the transaction is a legacy (i.e. ``type == 0``) + * transaction. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isLegacy() { + return (this.type === 0); + } + /** + * Returns true if the transaction is a Berlin (i.e. ``type == 1``) + * transaction. See [[link-eip-2070]]. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isBerlin() { + return (this.type === 1); + } + /** + * Returns true if the transaction is a London (i.e. ``type == 2``) + * transaction. See [[link-eip-1559]]. + * + * This provides a Type Guard that this transaction will have + * the ``null``-ness for hardfork-specific properties set correctly. + */ + isLondon() { + return (this.type === 2); + } + /** + * Returns true if hte transaction is a Cancun (i.e. ``type == 3``) + * transaction. See [[link-eip-4844]]. + */ + isCancun() { + return (this.type === 3); + } + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent() { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createRemovedTransactionFilter(this); + } + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assert */ .vA)(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createReorderedTransactionFilter(this, other); + } + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .assertArgument */ .MR)(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); + const tx = new TransactionResponse(this, this.provider); + tx.#startBlock = startBlock; + return tx; + } +} +function createOrphanedBlockFilter(block) { + return { orphan: "drop-block", hash: block.hash, number: block.number }; +} +function createReorderedTransactionFilter(tx, other) { + return { orphan: "reorder-transaction", tx, other }; +} +function createRemovedTransactionFilter(tx) { + return { orphan: "drop-transaction", tx }; +} +function createRemovedLogFilter(log) { + return { orphan: "drop-log", log: { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + address: log.address, + data: log.data, + topics: Object.freeze(log.topics.slice()), + index: log.index + } }; +} +//# sourceMappingURL=provider.js.map + +/***/ }), + +/***/ 8177: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $: () => (/* binding */ accessListify) +/* harmony export */ }); +/* harmony import */ var _address_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30031); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36212); + + +function accessSetify(addr, storageKeys) { + return { + address: (0,_address_index_js__WEBPACK_IMPORTED_MODULE_0__/* .getAddress */ .b)(addr), + storageKeys: storageKeys.map((storageKey, index) => { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .isHexString */ .Lo)(storageKey, 32), "invalid slot", `storageKeys[${index}]`, storageKey); + return storageKey.toLowerCase(); + }) + }; +} +/** + * Returns a [[AccessList]] from any ethers-supported access-list structure. + */ +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index) => { + if (Array.isArray(set)) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(set.length === 2, "invalid slot set", `value[${index}]`, set); + return accessSetify(set[0], set[1]); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(set != null && typeof (set) === "object", "invalid address-slot set", "value", value); + return accessSetify(set.address, set.storageKeys); + }); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .assertArgument */ .MR)(value != null && typeof (value) === "object", "invalid access list", "value", value); + const result = Object.keys(value).map((addr) => { + const storageKeys = value[addr].reduce((accum, storageKey) => { + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a, b) => (a.address.localeCompare(b.address))); + return result; +} +//# sourceMappingURL=accesslist.js.map + +/***/ }), + +/***/ 20415: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ K: () => (/* binding */ computeAddress), +/* harmony export */ x: () => (/* binding */ recoverAddress) +/* harmony export */ }); +/* harmony import */ var _address_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30031); +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15496); +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(15539); + + +/** + * Returns the address for the %%key%%. + * + * The key may be any standard form of public key or a private key. + */ +function computeAddress(key) { + let pubkey; + if (typeof (key) === "string") { + pubkey = _crypto_index_js__WEBPACK_IMPORTED_MODULE_0__/* .SigningKey */ .h.computePublicKey(key, false); + } + else { + pubkey = key.publicKey; + } + return (0,_address_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getAddress */ .b)((0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_2__/* .keccak256 */ .S)("0x" + pubkey.substring(4)).substring(26)); +} +/** + * Returns the recovered address for the private key that was + * used to sign %%digest%% that resulted in %%signature%%. + */ +function recoverAddress(digest, signature) { + return computeAddress(_crypto_index_js__WEBPACK_IMPORTED_MODULE_0__/* .SigningKey */ .h.recoverPublicKey(digest, signature)); +} +//# sourceMappingURL=address.js.map + +/***/ }), + +/***/ 79453: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Z: () => (/* binding */ Transaction) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/address/address.js +var address = __webpack_require__(30031); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/constants/addresses.js +var addresses = __webpack_require__(98982); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/sha2.js +var sha2 = __webpack_require__(68650); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/signature.js + 1 modules +var crypto_signature = __webpack_require__(20260); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/keccak.js + 1 modules +var keccak = __webpack_require__(15539); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/crypto/signing-key.js + 6 modules +var signing_key = __webpack_require__(15496); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var utils_data = __webpack_require__(36212); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/rlp-decode.js +//See: https://github.com/ethereum/wiki/wiki/RLP + + + +function hexlifyByte(value) { + let result = value.toString(16); + while (result.length < 2) { + result = "0" + result; + } + return "0x" + result; +} +function unarrayifyInteger(data, offset, length) { + let result = 0; + for (let i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; +} +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while (childOffset < offset + 1 + length) { + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + (0,errors/* assert */.vA)(childOffset <= offset + 1 + length, "child data too short", "BUFFER_OVERRUN", { + buffer: data, length, offset + }); + } + return { consumed: (1 + length), result: result }; +} +// returns { consumed: number, result: Object } +function _decode(data, offset) { + (0,errors/* assert */.vA)(data.length !== 0, "data too short", "BUFFER_OVERRUN", { + buffer: data, length: 0, offset: 1 + }); + const checkOffset = (offset) => { + (0,errors/* assert */.vA)(offset <= data.length, "data short segment too short", "BUFFER_OVERRUN", { + buffer: data, length: data.length, offset + }); + }; + // Array with extra length prefix + if (data[offset] >= 0xf8) { + const lengthLength = data[offset] - 0xf7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + const length = data[offset] - 0xc0; + checkOffset(offset + 1 + length); + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + const lengthLength = data[offset] - 0xb7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + const result = (0,utils_data/* hexlify */.c$)(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + const length = data[offset] - 0x80; + checkOffset(offset + 1 + length); + const result = (0,utils_data/* hexlify */.c$)(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: hexlifyByte(data[offset]) }; +} +/** + * Decodes %%data%% into the structured data it represents. + */ +function decodeRlp(_data) { + const data = (0,utils_data/* getBytes */.q5)(_data, "data"); + const decoded = _decode(data, 0); + (0,errors/* assertArgument */.MR)(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data); + return decoded.result; +} +//# sourceMappingURL=rlp-decode.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/rlp-encode.js +var rlp_encode = __webpack_require__(65735); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/transaction/accesslist.js +var accesslist = __webpack_require__(8177); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/transaction/address.js +var transaction_address = __webpack_require__(20415); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/transaction/transaction.js + + + + + + +const BN_0 = BigInt(0); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const BLOB_SIZE = 4096 * 32; +function getVersionedHash(version, hash) { + let versioned = version.toString(16); + while (versioned.length < 2) { + versioned = "0" + versioned; + } + versioned += (0,sha2/* sha256 */.s)(hash).substring(4); + return "0x" + versioned; +} +function handleAddress(value) { + if (value === "0x") { + return null; + } + return (0,address/* getAddress */.b)(value); +} +function handleAccessList(value, param) { + try { + return (0,accesslist/* accessListify */.$)(value); + } + catch (error) { + (0,errors/* assertArgument */.MR)(false, error.message, param, value); + } +} +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return (0,maths/* getNumber */.WZ)(_value, param); +} +function handleUint(_value, param) { + if (_value === "0x") { + return BN_0; + } + const value = (0,maths/* getBigInt */.Ab)(_value, param); + (0,errors/* assertArgument */.MR)(value <= BN_MAX_UINT, "value exceeds uint size", param, value); + return value; +} +function formatNumber(_value, name) { + const value = (0,maths/* getBigInt */.Ab)(_value, "value"); + const result = (0,maths/* toBeArray */.c4)(value); + (0,errors/* assertArgument */.MR)(result.length <= 32, `value too large`, `tx.${name}`, value); + return result; +} +function formatAccessList(value) { + return (0,accesslist/* accessListify */.$)(value).map((set) => [set.address, set.storageKeys]); +} +function formatHashes(value, param) { + (0,errors/* assertArgument */.MR)(Array.isArray(value), `invalid ${param}`, "value", value); + for (let i = 0; i < value.length; i++) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isHexString */.Lo)(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]); + } + return value; +} +function _parseLegacy(data) { + const fields = decodeRlp(data); + (0,errors/* assertArgument */.MR)(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data); + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: (0,utils_data/* hexlify */.c$)(fields[5]), + chainId: BN_0 + }; + // Legacy unsigned transaction + if (fields.length === 6) { + return tx; + } + const v = handleUint(fields[6], "v"); + const r = handleUint(fields[7], "r"); + const s = handleUint(fields[8], "s"); + if (r === BN_0 && s === BN_0) { + // EIP-155 unsigned transaction + tx.chainId = v; + } + else { + // Compute the EIP-155 chain ID (or 0 for legacy) + let chainId = (v - BN_35) / BN_2; + if (chainId < BN_0) { + chainId = BN_0; + } + tx.chainId = chainId; + // Signed Legacy Transaction + (0,errors/* assertArgument */.MR)(chainId !== BN_0 || (v === BN_27 || v === BN_28), "non-canonical legacy v", "v", fields[6]); + tx.signature = crypto_signature/* Signature */.t.from({ + r: (0,utils_data/* zeroPadValue */.nx)(fields[7], 32), + s: (0,utils_data/* zeroPadValue */.nx)(fields[8], 32), + v + }); + //tx.hash = keccak256(data); + } + return tx; +} +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + (tx.to || "0x"), + formatNumber(tx.value, "value"), + tx.data, + ]; + let chainId = BN_0; + if (tx.chainId != BN_0) { + // A chainId was provided; if non-zero we'll use EIP-155 + chainId = (0,maths/* getBigInt */.Ab)(tx.chainId, "tx.chainId"); + // We have a chainId in the tx and an EIP-155 v in the signature, + // make sure they agree with each other + (0,errors/* assertArgument */.MR)(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig); + } + else if (tx.signature) { + // No explicit chainId, but EIP-155 have a derived implicit chainId + const legacy = tx.signature.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + // Requesting an unsigned transaction + if (!sig) { + // We have an EIP-155 transaction (chainId was specified and non-zero) + if (chainId !== BN_0) { + fields.push((0,maths/* toBeArray */.c4)(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return (0,rlp_encode/* encodeRlp */.R)(fields); + } + // @TODO: We should probably check that tx.signature, chainId, and sig + // match but that logic could break existing code, so schedule + // this for the next major bump. + // Compute the EIP-155 v + let v = BigInt(27 + sig.yParity); + if (chainId !== BN_0) { + v = crypto_signature/* Signature */.t.getChainIdV(chainId, sig.v); + } + else if (BigInt(sig.v) !== v) { + (0,errors/* assertArgument */.MR)(false, "tx.chainId/sig.v mismatch", "sig", sig); + } + // Add the signature + fields.push((0,maths/* toBeArray */.c4)(v)); + fields.push((0,maths/* toBeArray */.c4)(sig.r)); + fields.push((0,maths/* toBeArray */.c4)(sig.s)); + return (0,rlp_encode/* encodeRlp */.R)(fields); +} +function _parseEipSignature(tx, fields) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + (0,errors/* assertArgument */.MR)(false, "invalid yParity", "yParity", fields[0]); + } + const r = (0,utils_data/* zeroPadValue */.nx)(fields[1], 32); + const s = (0,utils_data/* zeroPadValue */.nx)(fields[2], 32); + const signature = crypto_signature/* Signature */.t.from({ r, s, yParity }); + tx.signature = signature; +} +function _parseEip1559(data) { + const fields = decodeRlp((0,utils_data/* getBytes */.q5)(data).slice(1)); + (0,errors/* assertArgument */.MR)(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", (0,utils_data/* hexlify */.c$)(data)); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: (0,utils_data/* hexlify */.c$)(fields[7]), + accessList: handleAccessList(fields[8], "accessList"), + }; + // Unsigned EIP-1559 Transaction + if (fields.length === 9) { + return tx; + } + //tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(9)); + return tx; +} +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + (tx.to || "0x"), + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push((0,maths/* toBeArray */.c4)(sig.r)); + fields.push((0,maths/* toBeArray */.c4)(sig.s)); + } + return (0,utils_data/* concat */.xW)(["0x02", (0,rlp_encode/* encodeRlp */.R)(fields)]); +} +function _parseEip2930(data) { + const fields = decodeRlp((0,utils_data/* getBytes */.q5)(data).slice(1)); + (0,errors/* assertArgument */.MR)(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", (0,utils_data/* hexlify */.c$)(data)); + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: (0,utils_data/* hexlify */.c$)(fields[6]), + accessList: handleAccessList(fields[7], "accessList") + }; + // Unsigned EIP-2930 Transaction + if (fields.length === 8) { + return tx; + } + //tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(8)); + return tx; +} +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + (tx.to || "0x"), + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push((0,maths/* toBeArray */.c4)(sig.r)); + fields.push((0,maths/* toBeArray */.c4)(sig.s)); + } + return (0,utils_data/* concat */.xW)(["0x01", (0,rlp_encode/* encodeRlp */.R)(fields)]); +} +function _parseEip4844(data) { + let fields = decodeRlp((0,utils_data/* getBytes */.q5)(data).slice(1)); + let typeName = "3"; + let blobs = null; + // Parse the network format + if (fields.length === 4 && Array.isArray(fields[0])) { + typeName = "3 (network format)"; + const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3]; + (0,errors/* assertArgument */.MR)(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs); + (0,errors/* assertArgument */.MR)(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits); + (0,errors/* assertArgument */.MR)(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs); + (0,errors/* assertArgument */.MR)(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields); + (0,errors/* assertArgument */.MR)(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields); + blobs = []; + for (let i = 0; i < fields[1].length; i++) { + blobs.push({ + data: fBlobs[i], + commitment: fCommits[i], + proof: fProofs[i], + }); + } + fields = fields[0]; + } + (0,errors/* assertArgument */.MR)(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", (0,utils_data/* hexlify */.c$)(data)); + const tx = { + type: 3, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: (0,utils_data/* hexlify */.c$)(fields[7]), + accessList: handleAccessList(fields[8], "accessList"), + maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"), + blobVersionedHashes: fields[10] + }; + if (blobs) { + tx.blobs = blobs; + } + (0,errors/* assertArgument */.MR)(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data); + (0,errors/* assertArgument */.MR)(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data); + for (let i = 0; i < tx.blobVersionedHashes.length; i++) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isHexString */.Lo)(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data); + } + // Unsigned EIP-4844 Transaction + if (fields.length === 11) { + return tx; + } + // @TODO: Do we need to do this? This is only called internally + // and used to verify hashes; it might save time to not do this + //tx.hash = keccak256(concat([ "0x03", encodeRlp(fields) ])); + _parseEipSignature(tx, fields.slice(11)); + return tx; +} +function _serializeEip4844(tx, sig, blobs) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + (tx.to || addresses/* ZeroAddress */.j), + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []), + formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"), + formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes") + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push((0,maths/* toBeArray */.c4)(sig.r)); + fields.push((0,maths/* toBeArray */.c4)(sig.s)); + // We have blobs; return the network wrapped format + if (blobs) { + return (0,utils_data/* concat */.xW)([ + "0x03", + (0,rlp_encode/* encodeRlp */.R)([ + fields, + blobs.map((b) => b.data), + blobs.map((b) => b.commitment), + blobs.map((b) => b.proof), + ]) + ]); + } + } + return (0,utils_data/* concat */.xW)(["0x03", (0,rlp_encode/* encodeRlp */.R)(fields)]); +} +/** + * A **Transaction** describes an operation to be executed on + * Ethereum by an Externally Owned Account (EOA). It includes + * who (the [[to]] address), what (the [[data]]) and how much (the + * [[value]] in ether) the operation should entail. + * + * @example: + * tx = new Transaction() + * //_result: + * + * tx.data = "0x1234"; + * //_result: + */ +class Transaction { + #type; + #to; + #data; + #nonce; + #gasLimit; + #gasPrice; + #maxPriorityFeePerGas; + #maxFeePerGas; + #value; + #chainId; + #sig; + #accessList; + #maxFeePerBlobGas; + #blobVersionedHashes; + #kzg; + #blobs; + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type() { return this.#type; } + set type(value) { + switch (value) { + case null: + this.#type = null; + break; + case 0: + case "legacy": + this.#type = 0; + break; + case 1: + case "berlin": + case "eip-2930": + this.#type = 1; + break; + case 2: + case "london": + case "eip-1559": + this.#type = 2; + break; + case 3: + case "cancun": + case "eip-4844": + this.#type = 3; + break; + default: + (0,errors/* assertArgument */.MR)(false, "unsupported transaction type", "type", value); + } + } + /** + * The name of the transaction type. + */ + get typeName() { + switch (this.type) { + case 0: return "legacy"; + case 1: return "eip-2930"; + case 2: return "eip-1559"; + case 3: return "eip-4844"; + } + return null; + } + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to() { + const value = this.#to; + if (value == null && this.type === 3) { + return addresses/* ZeroAddress */.j; + } + return value; + } + set to(value) { + this.#to = (value == null) ? null : (0,address/* getAddress */.b)(value); + } + /** + * The transaction nonce. + */ + get nonce() { return this.#nonce; } + set nonce(value) { this.#nonce = (0,maths/* getNumber */.WZ)(value, "value"); } + /** + * The gas limit. + */ + get gasLimit() { return this.#gasLimit; } + set gasLimit(value) { this.#gasLimit = (0,maths/* getBigInt */.Ab)(value); } + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice() { + const value = this.#gasPrice; + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0; + } + return value; + } + set gasPrice(value) { + this.#gasPrice = (value == null) ? null : (0,maths/* getBigInt */.Ab)(value, "gasPrice"); + } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas() { + const value = this.#maxPriorityFeePerGas; + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0; + } + return null; + } + return value; + } + set maxPriorityFeePerGas(value) { + this.#maxPriorityFeePerGas = (value == null) ? null : (0,maths/* getBigInt */.Ab)(value, "maxPriorityFeePerGas"); + } + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas() { + const value = this.#maxFeePerGas; + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0; + } + return null; + } + return value; + } + set maxFeePerGas(value) { + this.#maxFeePerGas = (value == null) ? null : (0,maths/* getBigInt */.Ab)(value, "maxFeePerGas"); + } + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data() { return this.#data; } + set data(value) { this.#data = (0,utils_data/* hexlify */.c$)(value); } + /** + * The amount of ether (in wei) to send in this transactions. + */ + get value() { return this.#value; } + set value(value) { + this.#value = (0,maths/* getBigInt */.Ab)(value, "value"); + } + /** + * The chain ID this transaction is valid on. + */ + get chainId() { return this.#chainId; } + set chainId(value) { this.#chainId = (0,maths/* getBigInt */.Ab)(value); } + /** + * If signed, the signature for this transaction. + */ + get signature() { return this.#sig || null; } + set signature(value) { + this.#sig = (value == null) ? null : crypto_signature/* Signature */.t.from(value); + } + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList() { + const value = this.#accessList || null; + if (value == null) { + if (this.type === 1 || this.type === 2 || this.type === 3) { + // @TODO: in v7, this should assign the value or become + // a live object itself, otherwise mutation is inconsistent + return []; + } + return null; + } + return value; + } + set accessList(value) { + this.#accessList = (value == null) ? null : (0,accesslist/* accessListify */.$)(value); + } + /** + * The max fee per blob gas for Cancun transactions. + */ + get maxFeePerBlobGas() { + const value = this.#maxFeePerBlobGas; + if (value == null && this.type === 3) { + return BN_0; + } + return value; + } + set maxFeePerBlobGas(value) { + this.#maxFeePerBlobGas = (value == null) ? null : (0,maths/* getBigInt */.Ab)(value, "maxFeePerBlobGas"); + } + /** + * The BLOb versioned hashes for Cancun transactions. + */ + get blobVersionedHashes() { + // @TODO: Mutation is inconsistent; if unset, the returned value + // cannot mutate the object, if set it can + let value = this.#blobVersionedHashes; + if (value == null && this.type === 3) { + return []; + } + return value; + } + set blobVersionedHashes(value) { + if (value != null) { + (0,errors/* assertArgument */.MR)(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value); + value = value.slice(); + for (let i = 0; i < value.length; i++) { + (0,errors/* assertArgument */.MR)((0,utils_data/* isHexString */.Lo)(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]); + } + } + this.#blobVersionedHashes = value; + } + /** + * The BLObs for the Transaction, if any. + * + * If ``blobs`` is non-``null``, then the [[seriailized]] + * will return the network formatted sidecar, otherwise it + * will return the standard [[link-eip-2718]] payload. The + * [[unsignedSerialized]] is unaffected regardless. + * + * When setting ``blobs``, either fully valid [[Blob]] objects + * may be specified (i.e. correctly padded, with correct + * committments and proofs) or a raw [[BytesLike]] may + * be provided. + * + * If raw [[BytesLike]] are provided, the [[kzg]] property **must** + * be already set. The blob will be correctly padded and the + * [[KzgLibrary]] will be used to compute the committment and + * proof for the blob. + * + * A BLOb is a sequence of field elements, each of which must + * be within the BLS field modulo, so some additional processing + * may be required to encode arbitrary data to ensure each 32 byte + * field is within the valid range. + * + * Setting this automatically populates [[blobVersionedHashes]], + * overwriting any existing values. Setting this to ``null`` + * does **not** remove the [[blobVersionedHashes]], leaving them + * present. + */ + get blobs() { + if (this.#blobs == null) { + return null; + } + return this.#blobs.map((b) => Object.assign({}, b)); + } + set blobs(_blobs) { + if (_blobs == null) { + this.#blobs = null; + return; + } + const blobs = []; + const versionedHashes = []; + for (let i = 0; i < _blobs.length; i++) { + const blob = _blobs[i]; + if ((0,utils_data/* isBytesLike */.f)(blob)) { + (0,errors/* assert */.vA)(this.#kzg, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", { + operation: "set blobs()" + }); + let data = (0,utils_data/* getBytes */.q5)(blob); + (0,errors/* assertArgument */.MR)(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob); + // Pad blob if necessary + if (data.length !== BLOB_SIZE) { + const padded = new Uint8Array(BLOB_SIZE); + padded.set(data); + data = padded; + } + const commit = this.#kzg.blobToKzgCommitment(data); + const proof = (0,utils_data/* hexlify */.c$)(this.#kzg.computeBlobKzgProof(data, commit)); + blobs.push({ + data: (0,utils_data/* hexlify */.c$)(data), + commitment: (0,utils_data/* hexlify */.c$)(commit), + proof + }); + versionedHashes.push(getVersionedHash(1, commit)); + } + else { + const commit = (0,utils_data/* hexlify */.c$)(blob.commitment); + blobs.push({ + data: (0,utils_data/* hexlify */.c$)(blob.data), + commitment: commit, + proof: (0,utils_data/* hexlify */.c$)(blob.proof) + }); + versionedHashes.push(getVersionedHash(1, commit)); + } + } + this.#blobs = blobs; + this.#blobVersionedHashes = versionedHashes; + } + get kzg() { return this.#kzg; } + set kzg(kzg) { + this.#kzg = kzg; + } + /** + * Creates a new Transaction with default values. + */ + constructor() { + this.#type = null; + this.#to = null; + this.#nonce = 0; + this.#gasLimit = BN_0; + this.#gasPrice = null; + this.#maxPriorityFeePerGas = null; + this.#maxFeePerGas = null; + this.#data = "0x"; + this.#value = BN_0; + this.#chainId = BN_0; + this.#sig = null; + this.#accessList = null; + this.#maxFeePerBlobGas = null; + this.#blobVersionedHashes = null; + this.#blobs = null; + this.#kzg = null; + } + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash() { + if (this.signature == null) { + return null; + } + return (0,keccak/* keccak256 */.S)(this.#getSerialized(true, false)); + } + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash() { + return (0,keccak/* keccak256 */.S)(this.unsignedSerialized); + } + /** + * The sending address, if signed. Otherwise, ``null``. + */ + get from() { + if (this.signature == null) { + return null; + } + return (0,transaction_address/* recoverAddress */.x)(this.unsignedHash, this.signature); + } + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey() { + if (this.signature == null) { + return null; + } + return signing_key/* SigningKey */.h.recoverPublicKey(this.unsignedHash, this.signature); + } + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned() { + return this.signature != null; + } + #getSerialized(signed, sidecar) { + (0,errors/* assert */.vA)(!signed || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); + const sig = signed ? this.signature : null; + switch (this.inferType()) { + case 0: + return _serializeLegacy(this, sig); + case 1: + return _serializeEip2930(this, sig); + case 2: + return _serializeEip1559(this, sig); + case 3: + return _serializeEip4844(this, sig, sidecar ? this.blobs : null); + } + (0,errors/* assert */.vA)(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); + } + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized() { + return this.#getSerialized(true, true); + } + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized() { + return this.#getSerialized(false, false); + } + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType() { + const types = this.inferTypes(); + // Prefer London (EIP-1559) over Cancun (BLOb) + if (types.indexOf(2) >= 0) { + return 2; + } + // Return the highest inferred type + return (types.pop()); + } + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes() { + // Checks that there are no conflicting properties set + const hasGasPrice = this.gasPrice != null; + const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null); + const hasAccessList = (this.accessList != null); + const hasBlob = (this.#maxFeePerBlobGas != null || this.#blobVersionedHashes); + //if (hasGasPrice && hasFee) { + // throw new Error("transaction cannot have gasPrice and maxFeePerGas"); + //} + if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { + (0,errors/* assert */.vA)(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }); + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + (0,errors/* assert */.vA)(!hasFee || (this.type !== 0 && this.type !== 1), "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this }); + (0,errors/* assert */.vA)(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this }); + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasFee) { + types.push(2); + } + else if (hasGasPrice) { + types.push(1); + if (!hasAccessList) { + types.push(0); + } + } + else if (hasAccessList) { + types.push(1); + types.push(2); + } + else if (hasBlob && this.to) { + types.push(3); + } + else { + types.push(0); + types.push(1); + types.push(2); + types.push(3); + } + } + types.sort(); + return types; + } + /** + * Returns true if this transaction is a legacy transaction (i.e. + * ``type === 0``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isLegacy() { + return (this.type === 0); + } + /** + * Returns true if this transaction is berlin hardform transaction (i.e. + * ``type === 1``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isBerlin() { + return (this.type === 1); + } + /** + * Returns true if this transaction is london hardform transaction (i.e. + * ``type === 2``). + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isLondon() { + return (this.type === 2); + } + /** + * Returns true if this transaction is an [[link-eip-4844]] BLOB + * transaction. + * + * This provides a Type Guard that the related properties are + * non-null. + */ + isCancun() { + return (this.type === 3); + } + /** + * Create a copy of this transaciton. + */ + clone() { + return Transaction.from(this); + } + /** + * Return a JSON-friendly object. + */ + toJSON() { + const s = (v) => { + if (v == null) { + return null; + } + return v.toString(); + }; + return { + type: this.type, + to: this.to, + // from: this.from, + data: this.data, + nonce: this.nonce, + gasLimit: s(this.gasLimit), + gasPrice: s(this.gasPrice), + maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), + maxFeePerGas: s(this.maxFeePerGas), + value: s(this.value), + chainId: s(this.chainId), + sig: this.signature ? this.signature.toJSON() : null, + accessList: this.accessList + }; + } + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx) { + if (tx == null) { + return new Transaction(); + } + if (typeof (tx) === "string") { + const payload = (0,utils_data/* getBytes */.q5)(tx); + if (payload[0] >= 0x7f) { // @TODO: > vs >= ?? + return Transaction.from(_parseLegacy(payload)); + } + switch (payload[0]) { + case 1: return Transaction.from(_parseEip2930(payload)); + case 2: return Transaction.from(_parseEip1559(payload)); + case 3: return Transaction.from(_parseEip4844(payload)); + } + (0,errors/* assert */.vA)(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" }); + } + const result = new Transaction(); + if (tx.type != null) { + result.type = tx.type; + } + if (tx.to != null) { + result.to = tx.to; + } + if (tx.nonce != null) { + result.nonce = tx.nonce; + } + if (tx.gasLimit != null) { + result.gasLimit = tx.gasLimit; + } + if (tx.gasPrice != null) { + result.gasPrice = tx.gasPrice; + } + if (tx.maxPriorityFeePerGas != null) { + result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; + } + if (tx.maxFeePerGas != null) { + result.maxFeePerGas = tx.maxFeePerGas; + } + if (tx.maxFeePerBlobGas != null) { + result.maxFeePerBlobGas = tx.maxFeePerBlobGas; + } + if (tx.data != null) { + result.data = tx.data; + } + if (tx.value != null) { + result.value = tx.value; + } + if (tx.chainId != null) { + result.chainId = tx.chainId; + } + if (tx.signature != null) { + result.signature = crypto_signature/* Signature */.t.from(tx.signature); + } + if (tx.accessList != null) { + result.accessList = tx.accessList; + } + // This will get overwritten by blobs, if present + if (tx.blobVersionedHashes != null) { + result.blobVersionedHashes = tx.blobVersionedHashes; + } + // Make sure we assign the kzg before assigning blobs, which + // require the library in the event raw blob data is provided. + if (tx.kzg != null) { + result.kzg = tx.kzg; + } + if (tx.blobs != null) { + result.blobs = tx.blobs; + } + if (tx.hash != null) { + (0,errors/* assertArgument */.MR)(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx); + (0,errors/* assertArgument */.MR)(result.hash === tx.hash, "hash mismatch", "tx", tx); + } + if (tx.from != null) { + (0,errors/* assertArgument */.MR)(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx); + (0,errors/* assertArgument */.MR)(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + } + return result; + } +} +//# sourceMappingURL=transaction.js.map + +/***/ }), + +/***/ 36212: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Lm: () => (/* binding */ getBytesCopy), +/* harmony export */ Lo: () => (/* binding */ isHexString), +/* harmony export */ X_: () => (/* binding */ zeroPadBytes), +/* harmony export */ ZG: () => (/* binding */ dataSlice), +/* harmony export */ c$: () => (/* binding */ hexlify), +/* harmony export */ f: () => (/* binding */ isBytesLike), +/* harmony export */ nx: () => (/* binding */ zeroPadValue), +/* harmony export */ pO: () => (/* binding */ dataLength), +/* harmony export */ q5: () => (/* binding */ getBytes), +/* harmony export */ xW: () => (/* binding */ concat) +/* harmony export */ }); +/* unused harmony export stripZerosLeft */ +/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/** + * Some data helpers. + * + * + * @_subsection api/utils:Data Helpers [about-data] + */ + +function _getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, "invalid BytesLike value", name || "value", value); +} +/** + * Get a typed Uint8Array for %%value%%. If already a Uint8Array + * the original %%value%% is returned; if a copy is required use + * [[getBytesCopy]]. + * + * @see: getBytesCopy + */ +function getBytes(value, name) { + return _getBytes(value, name, false); +} +/** + * Get a typed Uint8Array for %%value%%, creating a copy if necessary + * to prevent any modifications of the returned value from being + * reflected elsewhere. + * + * @see: getBytes + */ +function getBytesCopy(value, name) { + return _getBytes(value, name, true); +} +/** + * Returns true if %%value%% is a valid [[HexString]]. + * + * If %%length%% is ``true`` or a //number//, it also checks that + * %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//) + * bytes of data (e.g. ``0x1234`` is 2 bytes). + */ +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof (length) === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && (value.length % 2) !== 0) { + return false; + } + return true; +} +/** + * Returns true if %%value%% is a valid representation of arbitrary + * data (i.e. a valid [[DataHexString]] or a Uint8Array). + */ +function isBytesLike(value) { + return (isHexString(value, true) || (value instanceof Uint8Array)); +} +const HexCharacters = "0123456789abcdef"; +/** + * Returns a [[DataHexString]] representation of %%data%%. + */ +function hexlify(data) { + const bytes = getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes.length; i++) { + const v = bytes[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; +} +/** + * Returns a [[DataHexString]] by concatenating all values + * within %%data%%. + */ +function concat(datas) { + return "0x" + datas.map((d) => hexlify(d).substring(2)).join(""); +} +/** + * Returns the length of %%data%%, in bytes. + */ +function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; + } + return getBytes(data).length; +} +/** + * Returns a [[DataHexString]] by slicing %%data%% from the %%start%% + * offset to the %%end%% offset. + * + * By default %%start%% is 0 and %%end%% is the length of %%data%%. + */ +function dataSlice(data, start, end) { + const bytes = getBytes(data); + if (end != null && end > bytes.length) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes, length: bytes.length, offset: end + }); + } + return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end)); +} +/** + * Return the [[DataHexString]] result by stripping all **leading** + ** zero bytes from %%data%%. + */ +function stripZerosLeft(data) { + let bytes = hexlify(data).substring(2); + while (bytes.startsWith("00")) { + bytes = bytes.substring(2); + } + return "0x" + bytes; +} +function zeroPad(data, length, left) { + const bytes = getBytes(data); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(length >= bytes.length, "padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes), + length: length, + offset: length + 1 + }); + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes, length - bytes.length); + } + else { + result.set(bytes, 0); + } + return hexlify(result); +} +/** + * Return the [[DataHexString]] of %%data%% padded on the **left** + * to %%length%% bytes. + * + * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is + * thrown. + * + * This pads data the same as **values** are in Solidity + * (e.g. ``uint128``). + */ +function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +/** + * Return the [[DataHexString]] of %%data%% padded on the **right** + * to %%length%% bytes. + * + * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is + * thrown. + * + * This pads data the same as **bytes** are in Solidity + * (e.g. ``bytes16``). + */ +function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} +//# sourceMappingURL=data.js.map + +/***/ }), + +/***/ 57339: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ E: () => (/* binding */ isCallException), +/* harmony export */ MR: () => (/* binding */ assertArgument), +/* harmony export */ SP: () => (/* binding */ assertNormalize), +/* harmony export */ bJ: () => (/* binding */ isError), +/* harmony export */ dd: () => (/* binding */ assertArgumentCount), +/* harmony export */ gk: () => (/* binding */ assertPrivate), +/* harmony export */ vA: () => (/* binding */ assert), +/* harmony export */ xz: () => (/* binding */ makeError) +/* harmony export */ }); +/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99529); +/* harmony import */ var _properties_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(88081); +/** + * All errors in ethers include properties to ensure they are both + * human-readable (i.e. ``.message``) and machine-readable (i.e. ``.code``). + * + * The [[isError]] function can be used to check the error ``code`` and + * provide a type guard for the properties present on that error interface. + * + * @_section: api/utils/errors:Errors [about-errors] + */ + + +function stringify(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[ " + (value.map(stringify)).join(", ") + " ]"; + } + if (value instanceof Uint8Array) { + const HEX = "0123456789abcdef"; + let result = "0x"; + for (let i = 0; i < value.length; i++) { + result += HEX[value[i] >> 4]; + result += HEX[value[i] & 0xf]; + } + return result; + } + if (typeof (value) === "object" && typeof (value.toJSON) === "function") { + return stringify(value.toJSON()); + } + switch (typeof (value)) { + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + return BigInt(value).toString(); + case "number": + return (value).toString(); + case "string": + return JSON.stringify(value); + case "object": { + const keys = Object.keys(value); + keys.sort(); + return "{ " + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(", ") + " }"; + } + } + return `[ COULD NOT SERIALIZE ]`; +} +/** + * Returns true if the %%error%% matches an error thrown by ethers + * that matches the error %%code%%. + * + * In TypeScript environments, this can be used to check that %%error%% + * matches an EthersError type, which means the expected properties will + * be set. + * + * @See [ErrorCodes](api:ErrorCode) + * @example + * try { + * // code.... + * } catch (e) { + * if (isError(e, "CALL_EXCEPTION")) { + * // The Type Guard has validated this object + * console.log(e.data); + * } + * } + */ +function isError(error, code) { + return (error && error.code === code); +} +/** + * Returns true if %%error%% is a [[CallExceptionError]. + */ +function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); +} +/** + * Returns a new Error configured to the format ethers emits errors, with + * the %%message%%, [[api:ErrorCode]] %%code%% and additional properties + * for the corresponding EthersError. + * + * Each error in ethers includes the version of ethers, a + * machine-readable [[ErrorCode]], and depending on %%code%%, additional + * required properties. The error message will also include the %%message%%, + * ethers version, %%code%% and all additional properties, serialized. + */ +function makeError(message, code, info) { + let shortMessage = message; + { + const details = []; + if (info) { + if ("message" in info || "code" in info || "name" in info) { + throw new Error(`value will overwrite populated values: ${stringify(info)}`); + } + for (const key in info) { + if (key === "shortMessage") { + continue; + } + const value = (info[key]); + // try { + details.push(key + "=" + stringify(value)); + // } catch (error: any) { + // console.log("MMM", error.message); + // details.push(key + "=[could not serialize object]"); + // } + } + } + details.push(`code=${code}`); + details.push(`version=${_version_js__WEBPACK_IMPORTED_MODULE_0__/* .version */ .r}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + let error; + switch (code) { + case "INVALID_ARGUMENT": + error = new TypeError(message); + break; + case "NUMERIC_FAULT": + case "BUFFER_OVERRUN": + error = new RangeError(message); + break; + default: + error = new Error(message); + } + (0,_properties_js__WEBPACK_IMPORTED_MODULE_1__/* .defineProperties */ .n)(error, { code }); + if (info) { + Object.assign(error, info); + } + if (error.shortMessage == null) { + (0,_properties_js__WEBPACK_IMPORTED_MODULE_1__/* .defineProperties */ .n)(error, { shortMessage }); + } + return error; +} +/** + * Throws an EthersError with %%message%%, %%code%% and additional error + * %%info%% when %%check%% is falsish.. + * + * @see [[api:makeError]] + */ +function assert(check, message, code, info) { + if (!check) { + throw makeError(message, code, info); + } +} +/** + * A simple helper to simply ensuring provided arguments match expected + * constraints, throwing if not. + * + * In TypeScript environments, the %%check%% has been asserted true, so + * any further code does not need additional compile-time checks. + */ +function assertArgument(check, message, name, value) { + assert(check, message, "INVALID_ARGUMENT", { argument: name, value: value }); +} +function assertArgumentCount(count, expectedCount, message) { + if (message == null) { + message = ""; + } + if (message) { + message = ": " + message; + } + assert(count >= expectedCount, "missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + assert(count <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); +} +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + // General test for normalize + /* c8 ignore start */ + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + ; + /* c8 ignore stop */ + if (form === "NFD") { + const check = String.fromCharCode(0xe9).normalize("NFD"); + const expected = String.fromCharCode(0x65, 0x0301); + /* c8 ignore start */ + if (check !== expected) { + throw new Error("broken"); + } + /* c8 ignore stop */ + } + accum.push(form); + } + catch (error) { } + return accum; +}, []); +/** + * Throws if the normalization %%form%% is not supported. + */ +function assertNormalize(form) { + assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", info: { form } + }); +} +/** + * Many classes use file-scoped values to guard the constructor, + * making it effectively private. This facilitates that pattern + * by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%, + * throwing if not, indicating the %%className%% if provided. + */ +function assertPrivate(givenGuard, guard, className) { + if (className == null) { + className = ""; + } + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); + } +} +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 99381: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ z: () => (/* binding */ EventPayload) +/* harmony export */ }); +/* harmony import */ var _properties_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88081); +/** + * Events allow for applications to use the observer pattern, which + * allows subscribing and publishing events, outside the normal + * execution paths. + * + * @_section api/utils/events:Events [about-events] + */ + +/** + * When an [[EventEmitterable]] triggers a [[Listener]], the + * callback always ahas one additional argument passed, which is + * an **EventPayload**. + */ +class EventPayload { + /** + * The event filter. + */ + filter; + /** + * The **EventEmitterable**. + */ + emitter; + #listener; + /** + * Create a new **EventPayload** for %%emitter%% with + * the %%listener%% and for %%filter%%. + */ + constructor(emitter, listener, filter) { + this.#listener = listener; + (0,_properties_js__WEBPACK_IMPORTED_MODULE_0__/* .defineProperties */ .n)(this, { emitter, filter }); + } + /** + * Unregister the triggered listener for future events. + */ + async removeListener() { + if (this.#listener == null) { + return; + } + await this.emitter.off(this.filter, this.#listener); + } +} +//# sourceMappingURL=events.js.map + +/***/ }), + +/***/ 27033: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ab: () => (/* binding */ getBigInt), +/* harmony export */ Dg: () => (/* binding */ toBigInt), +/* harmony export */ JJ: () => (/* binding */ toTwos), +/* harmony export */ Ro: () => (/* binding */ toNumber), +/* harmony export */ ST: () => (/* binding */ fromTwos), +/* harmony export */ WZ: () => (/* binding */ getNumber), +/* harmony export */ c4: () => (/* binding */ toBeArray), +/* harmony export */ dK: () => (/* binding */ mask), +/* harmony export */ nD: () => (/* binding */ toQuantity), +/* harmony export */ up: () => (/* binding */ toBeHex) +/* harmony export */ }); +/* unused harmony export getUint */ +/* harmony import */ var _data_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36212); +/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/** + * Some mathematic operations. + * + * @_subsection: api/utils:Math Helpers [about-maths] + */ + + +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +//const BN_Max256 = (BN_1 << BigInt(256)) - BN_1; +// IEEE 754 support 53-bits of mantissa +const maxValue = 0x1fffffffffffff; +/** + * Convert %%value%% from a twos-compliment representation of %%width%% + * bits to its value. + * + * If the highest bit is ``1``, the result will be negative. + */ +function fromTwos(_value, _width) { + const value = getUint(_value, "value"); + const width = BigInt(getNumber(_width, "width")); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)((value >> width) === BN_0, "overflow", "NUMERIC_FAULT", { + operation: "fromTwos", fault: "overflow", value: _value + }); + // Top bit set; treat as a negative value + if (value >> (width - BN_1)) { + const mask = (BN_1 << width) - BN_1; + return -(((~value) & mask) + BN_1); + } + return value; +} +/** + * Convert %%value%% to a twos-compliment representation of + * %%width%% bits. + * + * The result will always be positive. + */ +function toTwos(_value, _width) { + let value = getBigInt(_value, "value"); + const width = BigInt(getNumber(_width, "width")); + const limit = (BN_1 << (width - BN_1)); + if (value < BN_0) { + value = -value; + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(value <= limit, "too low", "NUMERIC_FAULT", { + operation: "toTwos", fault: "overflow", value: _value + }); + const mask = (BN_1 << width) - BN_1; + return ((~value) & mask) + BN_1; + } + else { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(value < limit, "too high", "NUMERIC_FAULT", { + operation: "toTwos", fault: "overflow", value: _value + }); + } + return value; +} +/** + * Mask %%value%% with a bitmask of %%bits%% ones. + */ +function mask(_value, _bits) { + const value = getUint(_value, "value"); + const bits = BigInt(getNumber(_bits, "bits")); + return value & ((BN_1 << bits) - BN_1); +} +/** + * Gets a BigInt from %%value%%. If it is an invalid value for + * a BigInt, then an ArgumentError will be thrown for %%name%%. + */ +function getBigInt(value, name) { + switch (typeof (value)) { + case "bigint": return value; + case "number": + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(Number.isInteger(value), "underflow", name || "value", value); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); + return BigInt(value); + case "string": + try { + if (value === "") { + throw new Error("empty string"); + } + if (value[0] === "-" && value[1] !== "-") { + return -BigInt(value.substring(1)); + } + return BigInt(value); + } + catch (e) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, `invalid BigNumberish string: ${e.message}`, name || "value", value); + } + } + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, "invalid BigNumberish value", name || "value", value); +} +/** + * Returns %%value%% as a bigint, validating it is valid as a bigint + * value and that it is positive. + */ +function getUint(value, name) { + const result = getBigInt(value, name); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(result >= BN_0, "unsigned value cannot be negative", "NUMERIC_FAULT", { + fault: "overflow", operation: "getUint", value + }); + return result; +} +const Nibbles = "0123456789abcdef"; +/* + * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. + */ +function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v of value) { + result += Nibbles[v >> 4]; + result += Nibbles[v & 0x0f]; + } + return BigInt(result); + } + return getBigInt(value); +} +/** + * Gets a //number// from %%value%%. If it is an invalid value for + * a //number//, then an ArgumentError will be thrown for %%name%%. + */ +function getNumber(value, name) { + switch (typeof (value)) { + case "bigint": + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); + return Number(value); + case "number": + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(Number.isInteger(value), "underflow", name || "value", value); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); + return value; + case "string": + try { + if (value === "") { + throw new Error("empty string"); + } + return getNumber(BigInt(value), name); + } + catch (e) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, `invalid numeric string: ${e.message}`, name || "value", value); + } + } + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, "invalid numeric value", name || "value", value); +} +/** + * Converts %%value%% to a number. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. Throws if the value is not safe. + */ +function toNumber(value) { + return getNumber(toBigInt(value)); +} +/** + * Converts %%value%% to a Big Endian hexstring, optionally padded to + * %%width%% bytes. + */ +function toBeHex(_value, _width) { + const value = getUint(_value, "value"); + let result = value.toString(16); + if (_width == null) { + // Ensure the value is of even length + if (result.length % 2) { + result = "0" + result; + } + } + else { + const width = getNumber(_width, "width"); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assert */ .vA)(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", { + operation: "toBeHex", + fault: "overflow", + value: _value + }); + // Pad the value to the required width + while (result.length < (width * 2)) { + result = "0" + result; + } + } + return "0x" + result; +} +/** + * Converts %%value%% to a Big Endian Uint8Array. + */ +function toBeArray(_value) { + const value = getUint(_value, "value"); + if (value === BN_0) { + return new Uint8Array([]); + } + let hex = value.toString(16); + if (hex.length % 2) { + hex = "0" + hex; + } + const result = new Uint8Array(hex.length / 2); + for (let i = 0; i < result.length; i++) { + const offset = i * 2; + result[i] = parseInt(hex.substring(offset, offset + 2), 16); + } + return result; +} +/** + * Returns a [[HexString]] for %%value%% safe to use as a //Quantity//. + * + * A //Quantity// does not have and leading 0 values unless the value is + * the literal value `0x0`. This is most commonly used for JSSON-RPC + * numeric values. + */ +function toQuantity(value) { + let result = (0,_data_js__WEBPACK_IMPORTED_MODULE_1__/* .hexlify */ .c$)((0,_data_js__WEBPACK_IMPORTED_MODULE_1__/* .isBytesLike */ .f)(value) ? value : toBeArray(value)).substring(2); + while (result.startsWith("0")) { + result = result.substring(1); + } + if (result === "") { + result = "0"; + } + return "0x" + result; +} +//# sourceMappingURL=maths.js.map + +/***/ }), + +/***/ 88081: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ k: () => (/* binding */ resolveProperties), +/* harmony export */ n: () => (/* binding */ defineProperties) +/* harmony export */ }); +/** + * Property helper functions. + * + * @_subsection api/utils:Properties [about-properties] + */ +function checkType(value, type, name) { + const types = type.split("|").map(t => t.trim()); + for (let i = 0; i < types.length; i++) { + switch (type) { + case "any": + return; + case "bigint": + case "boolean": + case "number": + case "string": + if (typeof (value) === type) { + return; + } + } + } + const error = new Error(`invalid value for type ${type}`); + error.code = "INVALID_ARGUMENT"; + error.argument = `value.${name}`; + error.value = value; + throw error; +} +/** + * Resolves to a new object that is a copy of %%value%%, but with all + * values resolved. + */ +async function resolveProperties(value) { + const keys = Object.keys(value); + const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); + return results.reduce((accum, v, index) => { + accum[keys[index]] = v; + return accum; + }, {}); +} +/** + * Assigns the %%values%% to %%target%% as read-only values. + * + * It %%types%% is specified, the values are checked. + */ +function defineProperties(target, values, types) { + for (let key in values) { + let value = values[key]; + const type = (types ? types[key] : null); + if (type) { + checkType(value, type, key); + } + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); + } +} +//# sourceMappingURL=properties.js.map + +/***/ }), + +/***/ 65735: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ R: () => (/* binding */ encodeRlp) +/* harmony export */ }); +/* harmony import */ var _data_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36212); +//See: https://github.com/ethereum/wiki/wiki/RLP + +function arrayifyInteger(value) { + const result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; +} +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + const length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + const data = Array.prototype.slice.call((0,_data_js__WEBPACK_IMPORTED_MODULE_0__/* .getBytes */ .q5)(object, "object")); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + const length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); +} +const nibbles = "0123456789abcdef"; +/** + * Encodes %%object%% as an RLP-encoded [[DataHexString]]. + */ +function encodeRlp(object) { + let result = "0x"; + for (const v of _encode(object)) { + result += nibbles[v >> 4]; + result += nibbles[v & 0xf]; + } + return result; +} +//# sourceMappingURL=rlp-encode.js.map + +/***/ }), + +/***/ 99770: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + g5: () => (/* binding */ parseEther), + XS: () => (/* binding */ parseUnits) +}); + +// UNUSED EXPORTS: formatEther, formatUnits + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/data.js +var data = __webpack_require__(36212); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/maths.js +var maths = __webpack_require__(27033); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/fixednumber.js +/** + * The **FixedNumber** class permits using values with decimal places, + * using fixed-pont math. + * + * Fixed-point math is still based on integers under-the-hood, but uses an + * internal offset to store fractional components below, and each operation + * corrects for this after each operation. + * + * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math] + */ + + + + +const BN_N1 = BigInt(-1); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_5 = BigInt(5); +const _guard = {}; +// Constant to pull zeros from for multipliers +let Zeros = "0000"; +while (Zeros.length < 80) { + Zeros += Zeros; +} +// Returns a string "1" followed by decimal "0"s +function getTens(decimals) { + let result = Zeros; + while (result.length < decimals) { + result += result; + } + return BigInt("1" + result.substring(0, decimals)); +} +function checkValue(val, format, safeOp) { + const width = BigInt(format.width); + if (format.signed) { + const limit = (BN_1 << (width - BN_1)); + (0,errors/* assert */.vA)(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", { + operation: safeOp, fault: "overflow", value: val + }); + if (val > BN_0) { + val = (0,maths/* fromTwos */.ST)((0,maths/* mask */.dK)(val, width), width); + } + else { + val = -(0,maths/* fromTwos */.ST)((0,maths/* mask */.dK)(-val, width), width); + } + } + else { + const limit = (BN_1 << width); + (0,errors/* assert */.vA)(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", { + operation: safeOp, fault: "overflow", value: val + }); + val = (((val % limit) + limit) % limit) & (limit - BN_1); + } + return val; +} +function getFormat(value) { + if (typeof (value) === "number") { + value = `fixed128x${value}`; + } + let signed = true; + let width = 128; + let decimals = 18; + if (typeof (value) === "string") { + // Parse the format string + if (value === "fixed") { + // defaults... + } + else if (value === "ufixed") { + signed = false; + } + else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + (0,errors/* assertArgument */.MR)(match, "invalid fixed format", "format", value); + signed = (match[1] !== "u"); + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } + else if (value) { + // Extract the values from the object + const v = value; + const check = (key, type, defaultValue) => { + if (v[key] == null) { + return defaultValue; + } + (0,errors/* assertArgument */.MR)(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]); + return v[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + (0,errors/* assertArgument */.MR)((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width); + (0,errors/* assertArgument */.MR)(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals); + const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + return { signed, width, decimals, name }; +} +function fixednumber_toString(val, decimals) { + let negative = ""; + if (val < BN_0) { + negative = "-"; + val *= BN_N1; + } + let str = val.toString(); + // No decimal point for whole values + if (decimals === 0) { + return (negative + str); + } + // Pad out to the whole component (including a whole digit) + while (str.length <= decimals) { + str = Zeros + str; + } + // Insert the decimal point + const index = str.length - decimals; + str = str.substring(0, index) + "." + str.substring(index); + // Trim the whole component (leaving at least one 0) + while (str[0] === "0" && str[1] !== ".") { + str = str.substring(1); + } + // Trim the decimal component (leaving at least one 0) + while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") { + str = str.substring(0, str.length - 1); + } + return (negative + str); +} +/** + * A FixedNumber represents a value over its [[FixedFormat]] + * arithmetic field. + * + * A FixedNumber can be used to perform math, losslessly, on + * values which have decmial places. + * + * A FixedNumber has a fixed bit-width to store values in, and stores all + * values internally by multiplying the value by 10 raised to the power of + * %%decimals%%. + * + * If operations are performed that cause a value to grow too high (close to + * positive infinity) or too low (close to negative infinity), the value + * is said to //overflow//. + * + * For example, an 8-bit signed value, with 0 decimals may only be within + * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become + * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``. + * + * Many operation have a normal and //unsafe// variant. The normal variant + * will throw a [[NumericFaultError]] on any overflow, while the //unsafe// + * variant will silently allow overflow, corrupting its value value. + * + * If operations are performed that cause a value to become too small + * (close to zero), the value loses precison and is said to //underflow//. + * + * For example, an value with 1 decimal place may store a number as small + * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit + * into 1 decimal place, so underflow occurs which means precision is lost + * and the value becomes ``0``. + * + * Some operations have a normal and //signalling// variant. The normal + * variant will silently ignore underflow, while the //signalling// variant + * will thow a [[NumericFaultError]] on underflow. + */ +class fixednumber_FixedNumber { + /** + * The specific fixed-point arithmetic field for this value. + */ + format; + #format; + // The actual value (accounting for decimals) + #val; + // A base-10 value to multiple values by to maintain the magnitude + #tens; + /** + * This is a property so console.log shows a human-meaningful value. + * + * @private + */ + _value; + // Use this when changing this file to get some typing info, + // but then switch to any to mask the internal type + //constructor(guard: any, value: bigint, format: _FixedFormat) { + /** + * @private + */ + constructor(guard, value, format) { + (0,errors/* assertPrivate */.gk)(guard, _guard, "FixedNumber"); + this.#val = value; + this.#format = format; + const _value = fixednumber_toString(value, format.decimals); + (0,properties/* defineProperties */.n)(this, { format: format.name, _value }); + this.#tens = getTens(format.decimals); + } + /** + * If true, negative values are permitted, otherwise only + * positive values and zero are allowed. + */ + get signed() { return this.#format.signed; } + /** + * The number of bits available to store the value. + */ + get width() { return this.#format.width; } + /** + * The number of decimal places in the fixed-point arithment field. + */ + get decimals() { return this.#format.decimals; } + /** + * The value as an integer, based on the smallest unit the + * [[decimals]] allow. + */ + get value() { return this.#val; } + #checkFormat(other) { + (0,errors/* assertArgument */.MR)(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other); + } + #checkValue(val, safeOp) { + /* + const width = BigInt(this.width); + if (this.signed) { + const limit = (BN_1 << (width - BN_1)); + assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", { + operation: safeOp, fault: "overflow", value: val + }); + + if (val > BN_0) { + val = fromTwos(mask(val, width), width); + } else { + val = -fromTwos(mask(-val, width), width); + } + + } else { + const masked = mask(val, width); + assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", { + operation: safeOp, fault: "overflow", value: val + }); + val = masked; + } + */ + val = checkValue(val, this.#format, safeOp); + return new fixednumber_FixedNumber(_guard, val, this.#format); + } + #add(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue(this.#val + o.#val, safeOp); + } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% added + * to %%other%%, ignoring overflow. + */ + addUnsafe(other) { return this.#add(other); } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% added + * to %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs. + */ + add(other) { return this.#add(other, "add"); } + #sub(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue(this.#val - o.#val, safeOp); + } + /** + * Returns a new [[FixedNumber]] with the result of %%other%% subtracted + * from %%this%%, ignoring overflow. + */ + subUnsafe(other) { return this.#sub(other); } + /** + * Returns a new [[FixedNumber]] with the result of %%other%% subtracted + * from %%this%%. A [[NumericFaultError]] is thrown if overflow + * occurs. + */ + sub(other) { return this.#sub(other, "sub"); } + #mul(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp); + } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%, ignoring overflow and underflow (precision loss). + */ + mulUnsafe(other) { return this.#mul(other); } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs. + */ + mul(other) { return this.#mul(other, "mul"); } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% multiplied + * by %%other%%. A [[NumericFaultError]] is thrown if overflow + * occurs or if underflow (precision loss) occurs. + */ + mulSignal(other) { + this.#checkFormat(other); + const value = this.#val * other.#val; + (0,errors/* assert */.vA)((value % this.#tens) === BN_0, "precision lost during signalling mul", "NUMERIC_FAULT", { + operation: "mulSignal", fault: "underflow", value: this + }); + return this.#checkValue(value / this.#tens, "mulSignal"); + } + #div(o, safeOp) { + (0,errors/* assert */.vA)(o.#val !== BN_0, "division by zero", "NUMERIC_FAULT", { + operation: "div", fault: "divide-by-zero", value: this + }); + this.#checkFormat(o); + return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp); + } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%, ignoring underflow (precision loss). A + * [[NumericFaultError]] is thrown if overflow occurs. + */ + divUnsafe(other) { return this.#div(other); } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%, ignoring underflow (precision loss). A + * [[NumericFaultError]] is thrown if overflow occurs. + */ + div(other) { return this.#div(other, "div"); } + /** + * Returns a new [[FixedNumber]] with the result of %%this%% divided + * by %%other%%. A [[NumericFaultError]] is thrown if underflow + * (precision loss) occurs. + */ + divSignal(other) { + (0,errors/* assert */.vA)(other.#val !== BN_0, "division by zero", "NUMERIC_FAULT", { + operation: "div", fault: "divide-by-zero", value: this + }); + this.#checkFormat(other); + const value = (this.#val * this.#tens); + (0,errors/* assert */.vA)((value % other.#val) === BN_0, "precision lost during signalling div", "NUMERIC_FAULT", { + operation: "divSignal", fault: "underflow", value: this + }); + return this.#checkValue(value / other.#val, "divSignal"); + } + /** + * Returns a comparison result between %%this%% and %%other%%. + * + * This is suitable for use in sorting, where ``-1`` implies %%this%% + * is smaller, ``1`` implies %%this%% is larger and ``0`` implies + * both are equal. + */ + cmp(other) { + let a = this.value, b = other.value; + // Coerce a and b to the same magnitude + const delta = this.decimals - other.decimals; + if (delta > 0) { + b *= getTens(delta); + } + else if (delta < 0) { + a *= getTens(-delta); + } + // Comnpare + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; + } + /** + * Returns true if %%other%% is equal to %%this%%. + */ + eq(other) { return this.cmp(other) === 0; } + /** + * Returns true if %%other%% is less than to %%this%%. + */ + lt(other) { return this.cmp(other) < 0; } + /** + * Returns true if %%other%% is less than or equal to %%this%%. + */ + lte(other) { return this.cmp(other) <= 0; } + /** + * Returns true if %%other%% is greater than to %%this%%. + */ + gt(other) { return this.cmp(other) > 0; } + /** + * Returns true if %%other%% is greater than or equal to %%this%%. + */ + gte(other) { return this.cmp(other) >= 0; } + /** + * Returns a new [[FixedNumber]] which is the largest **integer** + * that is less than or equal to %%this%%. + * + * The decimal component of the result will always be ``0``. + */ + floor() { + let val = this.#val; + if (this.#val < BN_0) { + val -= this.#tens - BN_1; + } + val = (this.#val / this.#tens) * this.#tens; + return this.#checkValue(val, "floor"); + } + /** + * Returns a new [[FixedNumber]] which is the smallest **integer** + * that is greater than or equal to %%this%%. + * + * The decimal component of the result will always be ``0``. + */ + ceiling() { + let val = this.#val; + if (this.#val > BN_0) { + val += this.#tens - BN_1; + } + val = (this.#val / this.#tens) * this.#tens; + return this.#checkValue(val, "ceiling"); + } + /** + * Returns a new [[FixedNumber]] with the decimal component + * rounded up on ties at %%decimals%% places. + */ + round(decimals) { + if (decimals == null) { + decimals = 0; + } + // Not enough precision to not already be rounded + if (decimals >= this.decimals) { + return this; + } + const delta = this.decimals - decimals; + const bump = BN_5 * getTens(delta - 1); + let value = this.value + bump; + const tens = getTens(delta); + value = (value / tens) * tens; + checkValue(value, this.#format, "round"); + return new fixednumber_FixedNumber(_guard, value, this.#format); + } + /** + * Returns true if %%this%% is equal to ``0``. + */ + isZero() { return (this.#val === BN_0); } + /** + * Returns true if %%this%% is less than ``0``. + */ + isNegative() { return (this.#val < BN_0); } + /** + * Returns the string representation of %%this%%. + */ + toString() { return this._value; } + /** + * Returns a float approximation. + * + * Due to IEEE 754 precission (or lack thereof), this function + * can only return an approximation and most values will contain + * rounding errors. + */ + toUnsafeFloat() { return parseFloat(this.toString()); } + /** + * Return a new [[FixedNumber]] with the same value but has had + * its field set to %%format%%. + * + * This will throw if the value cannot fit into %%format%%. + */ + toFormat(format) { + return fixednumber_FixedNumber.fromString(this.toString(), format); + } + /** + * Creates a new [[FixedNumber]] for %%value%% divided by + * %%decimal%% places with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% (once adjusted + * for %%decimals%%) cannot fit in %%format%%, either due to overflow + * or underflow (precision loss). + */ + static fromValue(_value, _decimals, _format) { + const decimals = (_decimals == null) ? 0 : (0,maths/* getNumber */.WZ)(_decimals); + const format = getFormat(_format); + let value = (0,maths/* getBigInt */.Ab)(_value, "value"); + const delta = decimals - format.decimals; + if (delta > 0) { + const tens = getTens(delta); + (0,errors/* assert */.vA)((value % tens) === BN_0, "value loses precision for format", "NUMERIC_FAULT", { + operation: "fromValue", fault: "underflow", value: _value + }); + value /= tens; + } + else if (delta < 0) { + value *= getTens(-delta); + } + checkValue(value, format, "fromValue"); + return new fixednumber_FixedNumber(_guard, value, format); + } + /** + * Creates a new [[FixedNumber]] for %%value%% with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% cannot fit + * in %%format%%, either due to overflow or underflow (precision loss). + */ + static fromString(_value, _format) { + const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/); + (0,errors/* assertArgument */.MR)(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value); + const format = getFormat(_format); + let whole = (match[2] || "0"), decimal = (match[3] || ""); + // Pad out the decimals + while (decimal.length < format.decimals) { + decimal += Zeros; + } + // Check precision is safe + (0,errors/* assert */.vA)(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", { + operation: "fromString", fault: "underflow", value: _value + }); + // Remove extra padding + decimal = decimal.substring(0, format.decimals); + const value = BigInt(match[1] + whole + decimal); + checkValue(value, format, "fromString"); + return new fixednumber_FixedNumber(_guard, value, format); + } + /** + * Creates a new [[FixedNumber]] with the big-endian representation + * %%value%% with %%format%%. + * + * This will throw a [[NumericFaultError]] if %%value%% cannot fit + * in %%format%% due to overflow. + */ + static fromBytes(_value, _format) { + let value = (0,maths/* toBigInt */.Dg)((0,data/* getBytes */.q5)(_value, "value")); + const format = getFormat(_format); + if (format.signed) { + value = (0,maths/* fromTwos */.ST)(value, format.width); + } + checkValue(value, format, "fromBytes"); + return new fixednumber_FixedNumber(_guard, value, format); + } +} +//const f1 = FixedNumber.fromString("12.56", "fixed16x2"); +//const f2 = FixedNumber.fromString("0.3", "fixed16x2"); +//console.log(f1.divSignal(f2)); +//const BUMP = FixedNumber.from("0.5"); +//# sourceMappingURL=fixednumber.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils/units.js +/** + * Most interactions with Ethereum requires integer values, which use + * the smallest magnitude unit. + * + * For example, imagine dealing with dollars and cents. Since dollars + * are divisible, non-integer values are possible, such as ``$10.77``. + * By using the smallest indivisible unit (i.e. cents), the value can + * be kept as the integer ``1077``. + * + * When receiving decimal input from the user (as a decimal string), + * the value should be converted to an integer and when showing a user + * a value, the integer value should be converted to a decimal string. + * + * This creates a clear distinction, between values to be used by code + * (integers) and values used for display logic to users (decimals). + * + * The native unit in Ethereum, //ether// is divisible to 18 decimal places, + * where each individual unit is called a //wei//. + * + * @_subsection api/utils:Unit Conversion [about-units] + */ + + + +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether", +]; +/** + * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal + * places. The %%unit%% may be the number of decimal places or the name of + * a unit (e.g. ``"gwei"`` for 9 decimal places). + * + */ +function formatUnits(value, unit) { + let decimals = 18; + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + assertArgument(index >= 0, "invalid unit", "unit", unit); + decimals = 3 * index; + } + else if (unit != null) { + decimals = getNumber(unit, "unit"); + } + return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString(); +} +/** + * Converts the //decimal string// %%value%% to a BigInt, assuming + * %%unit%% decimal places. The %%unit%% may the number of decimal places + * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places). + */ +function parseUnits(value, unit) { + (0,errors/* assertArgument */.MR)(typeof (value) === "string", "value must be a string", "value", value); + let decimals = 18; + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + (0,errors/* assertArgument */.MR)(index >= 0, "invalid unit", "unit", unit); + decimals = 3 * index; + } + else if (unit != null) { + decimals = (0,maths/* getNumber */.WZ)(unit, "unit"); + } + return fixednumber_FixedNumber.fromString(value, { decimals, width: 512 }).value; +} +/** + * Converts %%value%% into a //decimal string// using 18 decimal places. + */ +function formatEther(wei) { + return formatUnits(wei, 18); +} +/** + * Converts the //decimal string// %%ether%% to a BigInt, using 18 + * decimal places. + */ +function parseEther(ether) { + return parseUnits(ether, 18); +} +//# sourceMappingURL=units.js.map + +/***/ }), + +/***/ 87303: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ YW: () => (/* binding */ toUtf8Bytes), +/* harmony export */ _v: () => (/* binding */ toUtf8String) +/* harmony export */ }); +/* unused harmony exports Utf8ErrorFuncs, toUtf8CodePoints */ +/* harmony import */ var _data_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36212); +/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/** + * Using strings in Ethereum (or any security-basd system) requires + * additional care. These utilities attempt to mitigate some of the + * safety issues as well as provide the ability to recover and analyse + * strings. + * + * @_subsection api/utils:Strings and UTF-8 [about-strings] + */ + + +function errorFunc(reason, offset, bytes, output, badCodepoint) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === "OVERLONG") { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(typeof (badCodepoint) === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint); + output.push(badCodepoint); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +/** + * A handful of popular, built-in UTF-8 error handling strategies. + * + * **``"error"``** - throws on ANY illegal UTF-8 sequence or + * non-canonical (overlong) codepoints (this is the default) + * + * **``"ignore"``** - silently drops any illegal UTF-8 sequence + * and accepts non-canonical (overlong) codepoints + * + * **``"replace"``** - replace any illegal UTF-8 sequence with the + * UTF-8 replacement character (i.e. ``"\\ufffd"``) and accepts + * non-canonical (overlong) codepoints + * + * @returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc> + */ +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes = (0,_data_js__WEBPACK_IMPORTED_MODULE_1__/* .getBytes */ .q5)(_bytes, "bytes"); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } + else { + i += onError("BAD_PREFIX", i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +/** + * Returns the UTF-8 byte representation of %%str%%. + * + * If %%form%% is specified, the string is normalized. + */ +function toUtf8Bytes(str, form) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(typeof (str) === "string", "invalid string value", "str", str); + if (form != null) { + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertNormalize */ .SP)(form); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + (0,_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(i < str.length && ((c2 & 0xfc00) === 0xdc00), "invalid surrogate pair", "str", str); + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return new Uint8Array(result); +} +; +//export +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +/** + * Returns the string represented by the UTF-8 data %%bytes%%. + * + * When %%onError%% function is specified, it is called on UTF-8 + * errors allowing recovery using the [[Utf8ErrorFunc]] API. + * (default: [error](Utf8ErrorFuncs)) + */ +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +/** + * Returns the UTF-8 code-points for %%str%%. + * + * If %%form%% is specified, the string is normalized. + */ +function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +//# sourceMappingURL=utf8.js.map + +/***/ }), + +/***/ 37514: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ v: () => (/* binding */ Mnemonic) +/* harmony export */ }); +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(68650); +/* harmony import */ var _crypto_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(29851); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57339); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36212); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(88081); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(87303); +/* harmony import */ var _wordlists_lang_en_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(24636); + + + +// Returns a byte with the MSB bits set +function getUpperMask(bits) { + return ((1 << bits) - 1) << (8 - bits) & 0xff; +} +// Returns a byte with the LSB bits set +function getLowerMask(bits) { + return ((1 << bits) - 1) & 0xff; +} +function mnemonicToEntropy(mnemonic, wordlist) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertNormalize */ .SP)("NFKD"); + if (wordlist == null) { + wordlist = _wordlists_lang_en_js__WEBPACK_IMPORTED_MODULE_1__/* .LangEn */ .U.wordlist(); + } + const words = wordlist.split(mnemonic); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)((words.length % 3) === 0 && words.length >= 12 && words.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + const entropy = new Uint8Array(Math.ceil(11 * words.length / 8)); + let offset = 0; + for (let i = 0; i < words.length; i++) { + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(index >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + for (let bit = 0; bit < 11; bit++) { + if (index & (1 << (10 - bit))) { + entropy[offset >> 3] |= (1 << (7 - (offset % 8))); + } + offset++; + } + } + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytes */ .q5)((0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_3__/* .sha256 */ .s)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)(checksum === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + return (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .c$)(entropy.slice(0, entropyBits / 8)); +} +function entropyToMnemonic(entropy, wordlist) { + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertArgument */ .MR)((entropy.length % 4) === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]"); + if (wordlist == null) { + wordlist = _wordlists_lang_en_js__WEBPACK_IMPORTED_MODULE_1__/* .LangEn */ .U.wordlist(); + } + const indices = [0]; + let remainingBits = 11; + for (let i = 0; i < entropy.length; i++) { + // Consume the whole byte (with still more to go) + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + // This byte will complete an 11-bit index + } + else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); + // Start the next word + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } + } + // Compute the checksum bits + const checksumBits = entropy.length / 4; + const checksum = parseInt((0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_3__/* .sha256 */ .s)(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + // Shift the checksum into the word indices + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= (checksum >> (8 - checksumBits)); + return wordlist.join(indices.map((index) => wordlist.getWord(index))); +} +const _guard = {}; +/** + * A **Mnemonic** wraps all properties required to compute [[link-bip-39]] + * seeds and convert between phrases and entropy. + */ +class Mnemonic { + /** + * The mnemonic phrase of 12, 15, 18, 21 or 24 words. + * + * Use the [[wordlist]] ``split`` method to get the individual words. + */ + phrase; + /** + * The password used for this mnemonic. If no password is used this + * is the empty string (i.e. ``""``) as per the specification. + */ + password; + /** + * The wordlist for this mnemonic. + */ + wordlist; + /** + * The underlying entropy which the mnemonic encodes. + */ + entropy; + /** + * @private + */ + constructor(guard, entropy, phrase, password, wordlist) { + if (password == null) { + password = ""; + } + if (wordlist == null) { + wordlist = _wordlists_lang_en_js__WEBPACK_IMPORTED_MODULE_1__/* .LangEn */ .U.wordlist(); + } + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__/* .assertPrivate */ .gk)(guard, _guard, "Mnemonic"); + (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_4__/* .defineProperties */ .n)(this, { phrase, password, wordlist, entropy }); + } + /** + * Returns the seed for the mnemonic. + */ + computeSeed() { + const salt = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_5__/* .toUtf8Bytes */ .YW)("mnemonic" + this.password, "NFKD"); + return (0,_crypto_index_js__WEBPACK_IMPORTED_MODULE_6__/* .pbkdf2 */ .A)((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_5__/* .toUtf8Bytes */ .YW)(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); + } + /** + * Creates a new Mnemonic for the %%phrase%%. + * + * The default %%password%% is the empty string and the default + * wordlist is the [English wordlists](LangEn). + */ + static fromPhrase(phrase, password, wordlist) { + // Normalize the case and space; throws if invalid + const entropy = mnemonicToEntropy(phrase, wordlist); + phrase = entropyToMnemonic((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytes */ .q5)(entropy), wordlist); + return new Mnemonic(_guard, entropy, phrase, password, wordlist); + } + /** + * Create a new **Mnemonic** from the %%entropy%%. + * + * The default %%password%% is the empty string and the default + * wordlist is the [English wordlists](LangEn). + */ + static fromEntropy(_entropy, password, wordlist) { + const entropy = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytes */ .q5)(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist); + return new Mnemonic(_guard, (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .c$)(entropy), phrase, password, wordlist); + } + /** + * Returns the phrase for %%mnemonic%%. + */ + static entropyToPhrase(_entropy, wordlist) { + const entropy = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .getBytes */ .q5)(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist); + } + /** + * Returns the entropy for %%phrase%%. + */ + static phraseToEntropy(phrase, wordlist) { + return mnemonicToEntropy(phrase, wordlist); + } + /** + * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase. + * + * This checks all the provided words belong to the %%wordlist%%, + * that the length is valid and the checksum is correct. + */ + static isValidMnemonic(phrase, wordlist) { + try { + mnemonicToEntropy(phrase, wordlist); + return true; + } + catch (error) { } + return false; + } +} +//# sourceMappingURL=mnemonic.js.map + +/***/ }), + +/***/ 24636: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + U: () => (/* binding */ LangEn) +}); + +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/hash/id.js +var id = __webpack_require__(38264); +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/errors.js +var errors = __webpack_require__(57339); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wordlists/decode-owl.js + +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word) => { + if (word === sep) { + initial++; + } + else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } + else { + initial = 97; + accum.push(word); + } + return accum; + }, []); +} +/** + * @_ignore + */ +function decode(data, subs) { + // Replace all the substitutions with their expanded form + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + // Get all tle clumps; each suffix, first-increment and second-increment + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } + else { + clumps.push(item.toLowerCase()); + } + return ""; + }); + /* c8 ignore start */ + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + } + /* c8 ignore stop */ + return unfold(unfold(clumps, ";"), ":"); +} +/** + * @_ignore + */ +function decodeOwl(data) { + (0,errors/* assertArgument */.MR)(data[0] === "0", "unsupported auwl data", "data", data); + return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} +//# sourceMappingURL=decode-owl.js.map +// EXTERNAL MODULE: ./node_modules/ethers/lib.esm/utils/properties.js +var properties = __webpack_require__(88081); +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wordlists/wordlist.js + +/** + * A Wordlist represents a collection of language-specific + * words used to encode and devoce [[link-bip-39]] encoded data + * by mapping words to 11-bit values and vice versa. + */ +class Wordlist { + locale; + /** + * Creates a new Wordlist instance. + * + * Sub-classes MUST call this if they provide their own constructor, + * passing in the locale string of the language. + * + * Generally there is no need to create instances of a Wordlist, + * since each language-specific Wordlist creates an instance and + * there is no state kept internally, so they are safe to share. + */ + constructor(locale) { + (0,properties/* defineProperties */.n)(this, { locale }); + } + /** + * Sub-classes may override this to provide a language-specific + * method for spliting %%phrase%% into individual words. + * + * By default, %%phrase%% is split using any sequences of + * white-space as defined by regular expressions (i.e. ``/\s+/``). + */ + split(phrase) { + return phrase.toLowerCase().split(/\s+/g); + } + /** + * Sub-classes may override this to provider a language-specific + * method for joining %%words%% into a phrase. + * + * By default, %%words%% are joined by a single space. + */ + join(words) { + return words.join(" "); + } +} +//# sourceMappingURL=wordlist.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wordlists/wordlist-owl.js +// Use the encode-latin.js script to create the necessary +// data files to be consumed by this class + + + + +/** + * An OWL format Wordlist is an encoding method that exploits + * the general locality of alphabetically sorted words to + * achieve a simple but effective means of compression. + * + * This class is generally not useful to most developers as + * it is used mainly internally to keep Wordlists for languages + * based on ASCII-7 small. + * + * If necessary, there are tools within the ``generation/`` folder + * to create the necessary data. + */ +class WordlistOwl extends Wordlist { + #data; + #checksum; + /** + * Creates a new Wordlist for %%locale%% using the OWL %%data%% + * and validated against the %%checksum%%. + */ + constructor(locale, data, checksum) { + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + /** + * The OWL-encoded data. + */ + get _data() { return this.#data; } + /** + * Decode all the words for the wordlist. + */ + _decodeWords() { + return decodeOwl(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + // Verify the computed list matches the official list + const checksum = (0,id.id)(words.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + /* c8 ignore stop */ + this.#words = words; + } + return this.#words; + } + getWord(index) { + const words = this.#loadWords(); + (0,errors/* assertArgument */.MR)(index >= 0 && index < words.length, `invalid word index: ${index}`, "index", index); + return words[index]; + } + getWordIndex(word) { + return this.#loadWords().indexOf(word); + } +} +//# sourceMappingURL=wordlist-owl.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/wordlists/lang-en.js + +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +let wordlist = null; +/** + * The [[link-bip39-en]] for [mnemonic phrases](link-bip-39). + * + * @_docloc: api/wordlists + */ +class LangEn extends WordlistOwl { + /** + * Creates a new instance of the English language Wordlist. + * + * This should be unnecessary most of the time as the exported + * [[langEn]] should suffice. + * + * @_ignore: + */ + constructor() { super("en", words, checksum); } + /** + * Returns a singleton instance of a ``LangEn``, creating it + * if this is the first time being called. + */ + static wordlist() { + if (wordlist == null) { + wordlist = new LangEn(); + } + return wordlist; + } +} +//# sourceMappingURL=lang-en.js.map + +/***/ }), + +/***/ 27125: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CG: () => (/* binding */ output), +/* harmony export */ ai: () => (/* binding */ number), +/* harmony export */ ee: () => (/* binding */ bytes), +/* harmony export */ t2: () => (/* binding */ exists), +/* harmony export */ tW: () => (/* binding */ hash) +/* harmony export */ }); +/* unused harmony export bool */ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.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(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 }; +/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = ((/* unused pure expression or super */ null && (assert))); +//# sourceMappingURL=_assert.js.map + +/***/ }), + +/***/ 37171: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ D: () => (/* binding */ SHA2) +/* harmony export */ }); +/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27125); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10750); + + +// Polyfill for Safari 14 +function setBigUint64(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); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends _utils_js__WEBPACK_IMPORTED_MODULE_0__/* .Hash */ .Vw { + 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 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .createView */ .O8)(this.buffer); + } + update(data) { + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .exists */ .t2)(this); + const { view, buffer, blockLen } = this; + data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .toBytes */ .ZJ)(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 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .createView */ .O8)(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) { + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .exists */ .t2)(this); + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .output */ .CG)(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(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .createView */ .O8)(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; + } +} +//# sourceMappingURL=_sha2.js.map + +/***/ }), + +/***/ 86558: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ay: () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ B4: () => (/* binding */ rotlSL), +/* harmony export */ P5: () => (/* binding */ rotlSH), +/* harmony export */ WM: () => (/* binding */ rotlBH), +/* harmony export */ im: () => (/* binding */ rotlBL), +/* harmony export */ lD: () => (/* binding */ split) +/* harmony export */ }); +/* unused harmony exports fromBig, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, add, add3L, add3H, add4L, add4H, add5H, add5L */ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore + +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (u64); +//# sourceMappingURL=_u64.js.map + +/***/ }), + +/***/ 4655: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ w: () => (/* binding */ hmac) +/* harmony export */ }); +/* unused harmony export HMAC */ +/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27125); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10750); + + +// HMAC (RFC 2104) +class HMAC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__/* .Hash */ .Vw { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .hash */ .tW)(hash); + const key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .toBytes */ .ZJ)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .exists */ .t2)(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .exists */ .t2)(this); + (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__/* .bytes */ .ee)(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); +//# sourceMappingURL=hmac.js.map + +/***/ }), + +/***/ 84877: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ pbkdf2) +/* harmony export */ }); +/* unused harmony export pbkdf2Async */ +/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27125); +/* harmony import */ var _hmac_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4655); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10750); + + + +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__/* .hash */ .tW)(hash); + const opts = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .checkOpts */ .tY)({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai)(c); + (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai)(dkLen); + (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__/* .number */ .ai)(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .toBytes */ .ZJ)(_password); + const salt = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .toBytes */ .ZJ)(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = _hmac_js__WEBPACK_IMPORTED_MODULE_2__/* .hmac */ .w.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .createView */ .O8)(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map + +/***/ }), + +/***/ 3439: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ s: () => (/* binding */ sha256) +/* harmony export */ }); +/* unused harmony export sha224 */ +/* harmony import */ var _sha2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37171); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10750); + + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// 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); +// 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 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 _sha2_js__WEBPACK_IMPORTED_MODULE_0__/* .SHA2 */ .D { + 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 = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = 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 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(W15, 18) ^ (W15 >>> 3); + const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(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 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .rotr */ .Ow)(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); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .wrapConstructor */ .ld)(() => new SHA256()); +const sha224 = /* @__PURE__ */ (/* unused pure expression or super */ null && (wrapConstructor(() => new SHA224()))); +//# sourceMappingURL=sha256.js.map + +/***/ }), + +/***/ 10750: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Vw: () => (/* binding */ Hash), + $h: () => (/* binding */ asyncLoop), + tY: () => (/* binding */ checkOpts), + Id: () => (/* binding */ concatBytes), + O8: () => (/* binding */ createView), + po: () => (/* binding */ randomBytes), + Ow: () => (/* binding */ rotr), + ZJ: () => (/* binding */ toBytes), + DH: () => (/* binding */ u32), + ld: () => (/* binding */ wrapConstructor) +}); + +// UNUSED EXPORTS: bytesToHex, hexToBytes, isLE, nextTick, u8, utf8ToBytes, wrapConstructorWithOpts, wrapXOFConstructorWithOpts + +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/crypto.js +const crypto_crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; +//# sourceMappingURL=crypto.js.map +;// CONCATENATED MODULE: ./node_modules/ethers/node_modules/@noble/hashes/esm/utils.js +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. + +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (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); +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(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(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== '[object Object]') + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_crypto && typeof crypto_crypto.getRandomValues === 'function') { + return crypto_crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 2150: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Struct: () => (/* binding */ Struct), +/* harmony export */ StructError: () => (/* binding */ StructError), +/* harmony export */ any: () => (/* binding */ any), +/* harmony export */ array: () => (/* binding */ array), +/* harmony export */ assert: () => (/* binding */ assert), +/* harmony export */ assign: () => (/* binding */ assign), +/* harmony export */ bigint: () => (/* binding */ bigint), +/* harmony export */ boolean: () => (/* binding */ boolean), +/* harmony export */ coerce: () => (/* binding */ coerce), +/* harmony export */ create: () => (/* binding */ create), +/* harmony export */ date: () => (/* binding */ date), +/* harmony export */ defaulted: () => (/* binding */ defaulted), +/* harmony export */ define: () => (/* binding */ define), +/* harmony export */ deprecated: () => (/* binding */ deprecated), +/* harmony export */ dynamic: () => (/* binding */ dynamic), +/* harmony export */ empty: () => (/* binding */ empty), +/* harmony export */ enums: () => (/* binding */ enums), +/* harmony export */ func: () => (/* binding */ func), +/* harmony export */ instance: () => (/* binding */ instance), +/* harmony export */ integer: () => (/* binding */ integer), +/* harmony export */ intersection: () => (/* binding */ intersection), +/* harmony export */ is: () => (/* binding */ is), +/* harmony export */ lazy: () => (/* binding */ lazy), +/* harmony export */ literal: () => (/* binding */ literal), +/* harmony export */ map: () => (/* binding */ map), +/* harmony export */ mask: () => (/* binding */ mask), +/* harmony export */ max: () => (/* binding */ max), +/* harmony export */ min: () => (/* binding */ min), +/* harmony export */ never: () => (/* binding */ never), +/* harmony export */ nonempty: () => (/* binding */ nonempty), +/* harmony export */ nullable: () => (/* binding */ nullable), +/* harmony export */ number: () => (/* binding */ number), +/* harmony export */ object: () => (/* binding */ object), +/* harmony export */ omit: () => (/* binding */ omit), +/* harmony export */ optional: () => (/* binding */ optional), +/* harmony export */ partial: () => (/* binding */ partial), +/* harmony export */ pattern: () => (/* binding */ pattern), +/* harmony export */ pick: () => (/* binding */ pick), +/* harmony export */ record: () => (/* binding */ record), +/* harmony export */ refine: () => (/* binding */ refine), +/* harmony export */ regexp: () => (/* binding */ regexp), +/* harmony export */ set: () => (/* binding */ set), +/* harmony export */ size: () => (/* binding */ size), +/* harmony export */ string: () => (/* binding */ string), +/* harmony export */ struct: () => (/* binding */ struct), +/* harmony export */ trimmed: () => (/* binding */ trimmed), +/* harmony export */ tuple: () => (/* binding */ tuple), +/* harmony export */ type: () => (/* binding */ type), +/* harmony export */ union: () => (/* binding */ union), +/* harmony export */ unknown: () => (/* binding */ unknown), +/* harmony export */ validate: () => (/* binding */ validate) +/* harmony export */ }); +/* provided dependency */ var console = __webpack_require__(96763); +/** + * A `StructFailure` represents a single specific failure in validation. + */ +/** + * `StructError` objects are thrown (or returned) when validation fails. + * + * Validation logic is design to exit early for maximum performance. The error + * represents the first error encountered during validation. For more detail, + * the `error.failures` property is a generator function that can be run to + * continue validation and receive all the failures in the data. + */ +class StructError extends TypeError { + constructor(failure, failures) { + let cached; + const { message, explanation, ...rest } = failure; + const { path } = failure; + const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`; + super(explanation ?? msg); + if (explanation != null) + this.cause = msg; + Object.assign(this, rest); + this.name = this.constructor.name; + this.failures = () => { + return (cached ?? (cached = [failure, ...failures()])); + }; + } +} + +/** + * Check if a value is an iterator. + */ +function isIterable(x) { + return isObject(x) && typeof x[Symbol.iterator] === 'function'; +} +/** + * Check if a value is a plain object. + */ +function isObject(x) { + return typeof x === 'object' && x != null; +} +/** + * Check if a value is a plain object. + */ +function isPlainObject(x) { + if (Object.prototype.toString.call(x) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(x); + return prototype === null || prototype === Object.prototype; +} +/** + * Return a value as a printable string. + */ +function print(value) { + if (typeof value === 'symbol') { + return value.toString(); + } + return typeof value === 'string' ? JSON.stringify(value) : `${value}`; +} +/** + * Shifts (removes and returns) the first value from the `input` iterator. + * Like `Array.prototype.shift()` but for an `Iterator`. + */ +function shiftIterator(input) { + const { done, value } = input.next(); + return done ? undefined : value; +} +/** + * Convert a single validation result to a failure. + */ +function toFailure(result, context, struct, value) { + if (result === true) { + return; + } + else if (result === false) { + result = {}; + } + else if (typeof result === 'string') { + result = { message: result }; + } + const { path, branch } = context; + const { type } = struct; + const { refinement, message = `Expected a value of type \`${type}\`${refinement ? ` with refinement \`${refinement}\`` : ''}, but received: \`${print(value)}\``, } = result; + return { + value, + type, + refinement, + key: path[path.length - 1], + path, + branch, + ...result, + message, + }; +} +/** + * Convert a validation result to an iterable of failures. + */ +function* toFailures(result, context, struct, value) { + if (!isIterable(result)) { + result = [result]; + } + for (const r of result) { + const failure = toFailure(r, context, struct, value); + if (failure) { + yield failure; + } + } +} +/** + * Check a value against a struct, traversing deeply into nested values, and + * returning an iterator of failures or success. + */ +function* run(value, struct, options = {}) { + const { path = [], branch = [value], coerce = false, mask = false } = options; + const ctx = { path, branch }; + if (coerce) { + value = struct.coercer(value, ctx); + if (mask && + struct.type !== 'type' && + isObject(struct.schema) && + isObject(value) && + !Array.isArray(value)) { + for (const key in value) { + if (struct.schema[key] === undefined) { + delete value[key]; + } + } + } + } + let status = 'valid'; + for (const failure of struct.validator(value, ctx)) { + failure.explanation = options.message; + status = 'not_valid'; + yield [failure, undefined]; + } + for (let [k, v, s] of struct.entries(value, ctx)) { + const ts = run(v, s, { + path: k === undefined ? path : [...path, k], + branch: k === undefined ? branch : [...branch, v], + coerce, + mask, + message: options.message, + }); + for (const t of ts) { + if (t[0]) { + status = t[0].refinement != null ? 'not_refined' : 'not_valid'; + yield [t[0], undefined]; + } + else if (coerce) { + v = t[1]; + if (k === undefined) { + value = v; + } + else if (value instanceof Map) { + value.set(k, v); + } + else if (value instanceof Set) { + value.add(v); + } + else if (isObject(value)) { + if (v !== undefined || k in value) + value[k] = v; + } + } + } + } + if (status !== 'not_valid') { + for (const failure of struct.refiner(value, ctx)) { + failure.explanation = options.message; + status = 'not_refined'; + yield [failure, undefined]; + } + } + if (status === 'valid') { + yield [undefined, value]; + } +} + +/** + * `Struct` objects encapsulate the validation logic for a specific type of + * values. Once constructed, you use the `assert`, `is` or `validate` helpers to + * validate unknown input data against the struct. + */ +class Struct { + constructor(props) { + const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props; + this.type = type; + this.schema = schema; + this.entries = entries; + this.coercer = coercer; + if (validator) { + this.validator = (value, context) => { + const result = validator(value, context); + return toFailures(result, context, this, value); + }; + } + else { + this.validator = () => []; + } + if (refiner) { + this.refiner = (value, context) => { + const result = refiner(value, context); + return toFailures(result, context, this, value); + }; + } + else { + this.refiner = () => []; + } + } + /** + * Assert that a value passes the struct's validation, throwing if it doesn't. + */ + assert(value, message) { + return assert(value, this, message); + } + /** + * Create a value with the struct's coercion logic, then validate it. + */ + create(value, message) { + return create(value, this, message); + } + /** + * Check if a value passes the struct's validation. + */ + is(value) { + return is(value, this); + } + /** + * Mask a value, coercing and validating it, but returning only the subset of + * properties defined by the struct's schema. + */ + mask(value, message) { + return mask(value, this, message); + } + /** + * Validate a value with the struct's validation logic, returning a tuple + * representing the result. + * + * You may optionally pass `true` for the `withCoercion` argument to coerce + * the value before attempting to validate it. If you do, the result will + * contain the coerced result when successful. + */ + validate(value, options = {}) { + return validate(value, this, options); + } +} +/** + * Assert that a value passes a struct, throwing if it doesn't. + */ +function assert(value, struct, message) { + const result = validate(value, struct, { message }); + if (result[0]) { + throw result[0]; + } +} +/** + * Create a value with the coercion logic of struct and validate it. + */ +function create(value, struct, message) { + const result = validate(value, struct, { coerce: true, message }); + if (result[0]) { + throw result[0]; + } + else { + return result[1]; + } +} +/** + * Mask a value, returning only the subset of properties defined by a struct. + */ +function mask(value, struct, message) { + const result = validate(value, struct, { coerce: true, mask: true, message }); + if (result[0]) { + throw result[0]; + } + else { + return result[1]; + } +} +/** + * Check if a value passes a struct. + */ +function is(value, struct) { + const result = validate(value, struct); + return !result[0]; +} +/** + * Validate a value against a struct, returning an error if invalid, or the + * value (with potential coercion) if valid. + */ +function validate(value, struct, options = {}) { + const tuples = run(value, struct, options); + const tuple = shiftIterator(tuples); + if (tuple[0]) { + const error = new StructError(tuple[0], function* () { + for (const t of tuples) { + if (t[0]) { + yield t[0]; + } + } + }); + return [error, undefined]; + } + else { + const v = tuple[1]; + return [undefined, v]; + } +} + +function assign(...Structs) { + const isType = Structs[0].type === 'type'; + const schemas = Structs.map((s) => s.schema); + const schema = Object.assign({}, ...schemas); + return isType ? type(schema) : object(schema); +} +/** + * Define a new struct type with a custom validation function. + */ +function define(name, validator) { + return new Struct({ type: name, schema: null, validator }); +} +/** + * Create a new struct based on an existing struct, but the value is allowed to + * be `undefined`. `log` will be called if the value is not `undefined`. + */ +function deprecated(struct, log) { + return new Struct({ + ...struct, + refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), + validator(value, ctx) { + if (value === undefined) { + return true; + } + else { + log(value, ctx); + return struct.validator(value, ctx); + } + }, + }); +} +/** + * Create a struct with dynamic validation logic. + * + * The callback will receive the value currently being validated, and must + * return a struct object to validate it with. This can be useful to model + * validation logic that changes based on its input. + */ +function dynamic(fn) { + return new Struct({ + type: 'dynamic', + schema: null, + *entries(value, ctx) { + const struct = fn(value, ctx); + yield* struct.entries(value, ctx); + }, + validator(value, ctx) { + const struct = fn(value, ctx); + return struct.validator(value, ctx); + }, + coercer(value, ctx) { + const struct = fn(value, ctx); + return struct.coercer(value, ctx); + }, + refiner(value, ctx) { + const struct = fn(value, ctx); + return struct.refiner(value, ctx); + }, + }); +} +/** + * Create a struct with lazily evaluated validation logic. + * + * The first time validation is run with the struct, the callback will be called + * and must return a struct object to use. This is useful for cases where you + * want to have self-referential structs for nested data structures to avoid a + * circular definition problem. + */ +function lazy(fn) { + let struct; + return new Struct({ + type: 'lazy', + schema: null, + *entries(value, ctx) { + struct ?? (struct = fn()); + yield* struct.entries(value, ctx); + }, + validator(value, ctx) { + struct ?? (struct = fn()); + return struct.validator(value, ctx); + }, + coercer(value, ctx) { + struct ?? (struct = fn()); + return struct.coercer(value, ctx); + }, + refiner(value, ctx) { + struct ?? (struct = fn()); + return struct.refiner(value, ctx); + }, + }); +} +/** + * Create a new struct based on an existing object struct, but excluding + * specific properties. + * + * Like TypeScript's `Omit` utility. + */ +function omit(struct, keys) { + const { schema } = struct; + const subschema = { ...schema }; + for (const key of keys) { + delete subschema[key]; + } + switch (struct.type) { + case 'type': + return type(subschema); + default: + return object(subschema); + } +} +/** + * Create a new struct based on an existing object struct, but with all of its + * properties allowed to be `undefined`. + * + * Like TypeScript's `Partial` utility. + */ +function partial(struct) { + const isStruct = struct instanceof Struct; + const schema = isStruct ? { ...struct.schema } : { ...struct }; + for (const key in schema) { + schema[key] = optional(schema[key]); + } + if (isStruct && struct.type === 'type') { + return type(schema); + } + return object(schema); +} +/** + * Create a new struct based on an existing object struct, but only including + * specific properties. + * + * Like TypeScript's `Pick` utility. + */ +function pick(struct, keys) { + const { schema } = struct; + const subschema = {}; + for (const key of keys) { + subschema[key] = schema[key]; + } + switch (struct.type) { + case 'type': + return type(subschema); + default: + return object(subschema); + } +} +/** + * Define a new struct type with a custom validation function. + * + * @deprecated This function has been renamed to `define`. + */ +function struct(name, validator) { + console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.'); + return define(name, validator); +} + +/** + * Ensure that any value passes validation. + */ +function any() { + return define('any', () => true); +} +function array(Element) { + return new Struct({ + type: 'array', + schema: Element, + *entries(value) { + if (Element && Array.isArray(value)) { + for (const [i, v] of value.entries()) { + yield [i, v, Element]; + } + } + }, + coercer(value) { + return Array.isArray(value) ? value.slice() : value; + }, + validator(value) { + return (Array.isArray(value) || + `Expected an array value, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that a value is a bigint. + */ +function bigint() { + return define('bigint', (value) => { + return typeof value === 'bigint'; + }); +} +/** + * Ensure that a value is a boolean. + */ +function boolean() { + return define('boolean', (value) => { + return typeof value === 'boolean'; + }); +} +/** + * Ensure that a value is a valid `Date`. + * + * Note: this also ensures that the value is *not* an invalid `Date` object, + * which can occur when parsing a date fails but still returns a `Date`. + */ +function date() { + return define('date', (value) => { + return ((value instanceof Date && !isNaN(value.getTime())) || + `Expected a valid \`Date\` object, but received: ${print(value)}`); + }); +} +function enums(values) { + const schema = {}; + const description = values.map((v) => print(v)).join(); + for (const key of values) { + schema[key] = key; + } + return new Struct({ + type: 'enums', + schema, + validator(value) { + return (values.includes(value) || + `Expected one of \`${description}\`, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that a value is a function. + */ +function func() { + return define('func', (value) => { + return (typeof value === 'function' || + `Expected a function, but received: ${print(value)}`); + }); +} +/** + * Ensure that a value is an instance of a specific class. + */ +function instance(Class) { + return define('instance', (value) => { + return (value instanceof Class || + `Expected a \`${Class.name}\` instance, but received: ${print(value)}`); + }); +} +/** + * Ensure that a value is an integer. + */ +function integer() { + return define('integer', (value) => { + return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) || + `Expected an integer, but received: ${print(value)}`); + }); +} +/** + * Ensure that a value matches all of a set of types. + */ +function intersection(Structs) { + return new Struct({ + type: 'intersection', + schema: null, + *entries(value, ctx) { + for (const S of Structs) { + yield* S.entries(value, ctx); + } + }, + *validator(value, ctx) { + for (const S of Structs) { + yield* S.validator(value, ctx); + } + }, + *refiner(value, ctx) { + for (const S of Structs) { + yield* S.refiner(value, ctx); + } + }, + }); +} +function literal(constant) { + const description = print(constant); + const t = typeof constant; + return new Struct({ + type: 'literal', + schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null, + validator(value) { + return (value === constant || + `Expected the literal \`${description}\`, but received: ${print(value)}`); + }, + }); +} +function map(Key, Value) { + return new Struct({ + type: 'map', + schema: null, + *entries(value) { + if (Key && Value && value instanceof Map) { + for (const [k, v] of value.entries()) { + yield [k, k, Key]; + yield [k, v, Value]; + } + } + }, + coercer(value) { + return value instanceof Map ? new Map(value) : value; + }, + validator(value) { + return (value instanceof Map || + `Expected a \`Map\` object, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that no value ever passes validation. + */ +function never() { + return define('never', () => false); +} +/** + * Augment an existing struct to allow `null` values. + */ +function nullable(struct) { + return new Struct({ + ...struct, + validator: (value, ctx) => value === null || struct.validator(value, ctx), + refiner: (value, ctx) => value === null || struct.refiner(value, ctx), + }); +} +/** + * Ensure that a value is a number. + */ +function number() { + return define('number', (value) => { + return ((typeof value === 'number' && !isNaN(value)) || + `Expected a number, but received: ${print(value)}`); + }); +} +function object(schema) { + const knowns = schema ? Object.keys(schema) : []; + const Never = never(); + return new Struct({ + type: 'object', + schema: schema ? schema : null, + *entries(value) { + if (schema && isObject(value)) { + const unknowns = new Set(Object.keys(value)); + for (const key of knowns) { + unknowns.delete(key); + yield [key, value[key], schema[key]]; + } + for (const key of unknowns) { + yield [key, value[key], Never]; + } + } + }, + validator(value) { + return (isObject(value) || `Expected an object, but received: ${print(value)}`); + }, + coercer(value) { + return isObject(value) ? { ...value } : value; + }, + }); +} +/** + * Augment a struct to allow `undefined` values. + */ +function optional(struct) { + return new Struct({ + ...struct, + validator: (value, ctx) => value === undefined || struct.validator(value, ctx), + refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx), + }); +} +/** + * Ensure that a value is an object with keys and values of specific types, but + * without ensuring any specific shape of properties. + * + * Like TypeScript's `Record` utility. + */ +function record(Key, Value) { + return new Struct({ + type: 'record', + schema: null, + *entries(value) { + if (isObject(value)) { + for (const k in value) { + const v = value[k]; + yield [k, k, Key]; + yield [k, v, Value]; + } + } + }, + validator(value) { + return (isObject(value) || `Expected an object, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that a value is a `RegExp`. + * + * Note: this does not test the value against the regular expression! For that + * you need to use the `pattern()` refinement. + */ +function regexp() { + return define('regexp', (value) => { + return value instanceof RegExp; + }); +} +function set(Element) { + return new Struct({ + type: 'set', + schema: null, + *entries(value) { + if (Element && value instanceof Set) { + for (const v of value) { + yield [v, v, Element]; + } + } + }, + coercer(value) { + return value instanceof Set ? new Set(value) : value; + }, + validator(value) { + return (value instanceof Set || + `Expected a \`Set\` object, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that a value is a string. + */ +function string() { + return define('string', (value) => { + return (typeof value === 'string' || + `Expected a string, but received: ${print(value)}`); + }); +} +/** + * Ensure that a value is a tuple of a specific length, and that each of its + * elements is of a specific type. + */ +function tuple(Structs) { + const Never = never(); + return new Struct({ + type: 'tuple', + schema: null, + *entries(value) { + if (Array.isArray(value)) { + const length = Math.max(Structs.length, value.length); + for (let i = 0; i < length; i++) { + yield [i, value[i], Structs[i] || Never]; + } + } + }, + validator(value) { + return (Array.isArray(value) || + `Expected an array, but received: ${print(value)}`); + }, + }); +} +/** + * Ensure that a value has a set of known properties of specific types. + * + * Note: Unrecognized properties are allowed and untouched. This is similar to + * how TypeScript's structural typing works. + */ +function type(schema) { + const keys = Object.keys(schema); + return new Struct({ + type: 'type', + schema, + *entries(value) { + if (isObject(value)) { + for (const k of keys) { + yield [k, value[k], schema[k]]; + } + } + }, + validator(value) { + return (isObject(value) || `Expected an object, but received: ${print(value)}`); + }, + coercer(value) { + return isObject(value) ? { ...value } : value; + }, + }); +} +/** + * Ensure that a value matches one of a set of types. + */ +function union(Structs) { + const description = Structs.map((s) => s.type).join(' | '); + return new Struct({ + type: 'union', + schema: null, + coercer(value) { + for (const S of Structs) { + const [error, coerced] = S.validate(value, { coerce: true }); + if (!error) { + return coerced; + } + } + return value; + }, + validator(value, ctx) { + const failures = []; + for (const S of Structs) { + const [...tuples] = run(value, S, ctx); + const [first] = tuples; + if (!first[0]) { + return []; + } + else { + for (const [failure] of tuples) { + if (failure) { + failures.push(failure); + } + } + } + } + return [ + `Expected the value to satisfy a union of \`${description}\`, but received: ${print(value)}`, + ...failures, + ]; + }, + }); +} +/** + * Ensure that any value passes validation, without widening its type to `any`. + */ +function unknown() { + return define('unknown', () => true); +} + +/** + * Augment a `Struct` to add an additional coercion step to its input. + * + * This allows you to transform input data before validating it, to increase the + * likelihood that it passes validation—for example for default values, parsing + * different formats, etc. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + */ +function coerce(struct, condition, coercer) { + return new Struct({ + ...struct, + coercer: (value, ctx) => { + return is(value, condition) + ? struct.coercer(coercer(value, ctx), ctx) + : struct.coercer(value, ctx); + }, + }); +} +/** + * Augment a struct to replace `undefined` values with a default. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + */ +function defaulted(struct, fallback, options = {}) { + return coerce(struct, unknown(), (x) => { + const f = typeof fallback === 'function' ? fallback() : fallback; + if (x === undefined) { + return f; + } + if (!options.strict && isPlainObject(x) && isPlainObject(f)) { + const ret = { ...x }; + let changed = false; + for (const key in f) { + if (ret[key] === undefined) { + ret[key] = f[key]; + changed = true; + } + } + if (changed) { + return ret; + } + } + return x; + }); +} +/** + * Augment a struct to trim string inputs. + * + * Note: You must use `create(value, Struct)` on the value to have the coercion + * take effect! Using simply `assert()` or `is()` will not use coercion. + */ +function trimmed(struct) { + return coerce(struct, string(), (x) => x.trim()); +} + +/** + * Ensure that a string, array, map, or set is empty. + */ +function empty(struct) { + return refine(struct, 'empty', (value) => { + const size = getSize(value); + return (size === 0 || + `Expected an empty ${struct.type} but received one with a size of \`${size}\``); + }); +} +function getSize(value) { + if (value instanceof Map || value instanceof Set) { + return value.size; + } + else { + return value.length; + } +} +/** + * Ensure that a number or date is below a threshold. + */ +function max(struct, threshold, options = {}) { + const { exclusive } = options; + return refine(struct, 'max', (value) => { + return exclusive + ? value < threshold + : value <= threshold || + `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \`${value}\``; + }); +} +/** + * Ensure that a number or date is above a threshold. + */ +function min(struct, threshold, options = {}) { + const { exclusive } = options; + return refine(struct, 'min', (value) => { + return exclusive + ? value > threshold + : value >= threshold || + `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \`${value}\``; + }); +} +/** + * Ensure that a string, array, map or set is not empty. + */ +function nonempty(struct) { + return refine(struct, 'nonempty', (value) => { + const size = getSize(value); + return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`); + }); +} +/** + * Ensure that a string matches a regular expression. + */ +function pattern(struct, regexp) { + return refine(struct, 'pattern', (value) => { + return (regexp.test(value) || + `Expected a ${struct.type} matching \`/${regexp.source}/\` but received "${value}"`); + }); +} +/** + * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`. + */ +function size(struct, min, max = min) { + const expected = `Expected a ${struct.type}`; + const of = min === max ? `of \`${min}\`` : `between \`${min}\` and \`${max}\``; + return refine(struct, 'size', (value) => { + if (typeof value === 'number' || value instanceof Date) { + return ((min <= value && value <= max) || + `${expected} ${of} but received \`${value}\``); + } + else if (value instanceof Map || value instanceof Set) { + const { size } = value; + return ((min <= size && size <= max) || + `${expected} with a size ${of} but received one with a size of \`${size}\``); + } + else { + const { length } = value; + return ((min <= length && length <= max) || + `${expected} with a length ${of} but received one with a length of \`${length}\``); + } + }); +} +/** + * Augment a `Struct` to add an additional refinement to the validation. + * + * The refiner function is guaranteed to receive a value of the struct's type, + * because the struct's existing validation will already have passed. This + * allows you to layer additional validation on top of existing structs. + */ +function refine(struct, name, refiner) { + return new Struct({ + ...struct, + *refiner(value, ctx) { + yield* struct.refiner(value, ctx); + const result = refiner(value, ctx); + const failures = toFailures(result, ctx, struct, value); + for (const failure of failures) { + yield { ...failure, refinement: name }; + } + }, + }); +} + + +//# sourceMappingURL=index.mjs.map + + +/***/ }), + +/***/ 63837: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}'); + +/***/ }), + +/***/ 72079: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}'); + +/***/ }), + +/***/ 3219: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}'); + +/***/ }), + +/***/ 62951: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}'); + +/***/ }), + +/***/ 64589: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}'); + +/***/ }), + +/***/ 23241: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}'); + +/***/ }), + +/***/ 1636: +/***/ ((module) => { + +"use strict"; +module.exports = {"rE":"6.5.5"}; + +/***/ }), + +/***/ 15579: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}'); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/amd options */ +/******/ (() => { +/******/ __webpack_require__.amdO = {}; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be in strict mode. +(() => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ BatchBlockService: () => (/* reexport safe */ _batch__WEBPACK_IMPORTED_MODULE_4__.B3), +/* harmony export */ BatchEventsService: () => (/* reexport safe */ _batch__WEBPACK_IMPORTED_MODULE_4__.JY), +/* harmony export */ BatchTransactionService: () => (/* reexport safe */ _batch__WEBPACK_IMPORTED_MODULE_4__.AF), +/* harmony export */ Deposit: () => (/* reexport safe */ _deposits__WEBPACK_IMPORTED_MODULE_6__.dA), +/* harmony export */ ENS__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.p2), +/* harmony export */ ERC20__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Xc), +/* harmony export */ GET_DEPOSITS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_DEPOSITS), +/* harmony export */ GET_ECHO_EVENTS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_ECHO_EVENTS), +/* harmony export */ GET_ENCRYPTED_NOTES: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_ENCRYPTED_NOTES), +/* harmony export */ GET_GOVERNANCE_APY: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_GOVERNANCE_APY), +/* harmony export */ GET_GOVERNANCE_EVENTS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_GOVERNANCE_EVENTS), +/* harmony export */ GET_NOTE_ACCOUNTS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_NOTE_ACCOUNTS), +/* harmony export */ GET_REGISTERED: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_REGISTERED), +/* harmony export */ GET_STATISTIC: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_STATISTIC), +/* harmony export */ GET_WITHDRAWALS: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.GET_WITHDRAWALS), +/* harmony export */ GasPriceOracle__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Hu), +/* harmony export */ Invoice: () => (/* reexport safe */ _deposits__WEBPACK_IMPORTED_MODULE_6__.qO), +/* harmony export */ MIN_STAKE_BALANCE: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.pO), +/* harmony export */ MerkleTreeService: () => (/* reexport safe */ _merkleTree__WEBPACK_IMPORTED_MODULE_9__.s), +/* harmony export */ Mimc: () => (/* reexport safe */ _mimc__WEBPACK_IMPORTED_MODULE_10__.p), +/* harmony export */ Multicall__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Q2), +/* harmony export */ NetId: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.zr), +/* harmony export */ NoteAccount: () => (/* reexport safe */ _encryptedNotes__WEBPACK_IMPORTED_MODULE_7__.Ad), +/* harmony export */ OffchainOracle__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Hk), +/* harmony export */ OvmGasPriceOracle__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Ld), +/* harmony export */ Pedersen: () => (/* reexport safe */ _pedersen__WEBPACK_IMPORTED_MODULE_14__.Hr), +/* harmony export */ RelayerClient: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.OR), +/* harmony export */ ReverseRecords__factory: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.Rp), +/* harmony export */ TokenPriceOracle: () => (/* reexport safe */ _prices__WEBPACK_IMPORTED_MODULE_15__.T), +/* harmony export */ TornadoBrowserProvider: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.D2), +/* harmony export */ TornadoFeeOracle: () => (/* reexport safe */ _fees__WEBPACK_IMPORTED_MODULE_8__.o), +/* harmony export */ TornadoRpcSigner: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.Vr), +/* harmony export */ TornadoVoidSigner: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.Gd), +/* harmony export */ TornadoWallet: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.nA), +/* harmony export */ TreeCache: () => (/* reexport safe */ _treeCache__WEBPACK_IMPORTED_MODULE_19__.v), +/* harmony export */ _META: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__._META), +/* harmony export */ addNetwork: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.AE), +/* harmony export */ ajv: () => (/* reexport safe */ _schemas__WEBPACK_IMPORTED_MODULE_2__.SS), +/* harmony export */ base64ToBytes: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.Kp), +/* harmony export */ bigIntReplacer: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.gn), +/* harmony export */ bnToBytes: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.jm), +/* harmony export */ buffPedersenHash: () => (/* reexport safe */ _pedersen__WEBPACK_IMPORTED_MODULE_14__.UB), +/* harmony export */ bufferToBytes: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.lY), +/* harmony export */ bytesToBN: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.Ju), +/* harmony export */ bytesToBase64: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__["if"]), +/* harmony export */ bytesToHex: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.My), +/* harmony export */ calculateScore: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.zy), +/* harmony export */ calculateSnarkProof: () => (/* reexport safe */ _websnark__WEBPACK_IMPORTED_MODULE_21__.i), +/* harmony export */ chunk: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.iv), +/* harmony export */ concatBytes: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.Id), +/* harmony export */ convertETHToTokenAmount: () => (/* reexport safe */ _fees__WEBPACK_IMPORTED_MODULE_8__.N), +/* harmony export */ createDeposit: () => (/* reexport safe */ _deposits__WEBPACK_IMPORTED_MODULE_6__.Hr), +/* harmony export */ crypto: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.Et), +/* harmony export */ customConfig: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.cX), +/* harmony export */ defaultConfig: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.sb), +/* harmony export */ defaultUserAgent: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.mJ), +/* harmony export */ download: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.RG), +/* harmony export */ enabledChains: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.Af), +/* harmony export */ existsAsync: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.hn), +/* harmony export */ factories: () => (/* reexport safe */ _typechain__WEBPACK_IMPORTED_MODULE_3__.XB), +/* harmony export */ fetch: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.hd), +/* harmony export */ fetchData: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.Fd), +/* harmony export */ fetchGetUrlFunc: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.uY), +/* harmony export */ getAllDeposits: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllDeposits), +/* harmony export */ getAllEncryptedNotes: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllEncryptedNotes), +/* harmony export */ getAllGovernanceEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllGovernanceEvents), +/* harmony export */ getAllGraphEchoEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllGraphEchoEvents), +/* harmony export */ getAllRegisters: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllRegisters), +/* harmony export */ getAllWithdrawals: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getAllWithdrawals), +/* harmony export */ getConfig: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.zj), +/* harmony export */ getDeposits: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getDeposits), +/* harmony export */ getEncryptedNotes: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getEncryptedNotes), +/* harmony export */ getGasOraclePlugin: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.bD), +/* harmony export */ getGovernanceEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getGovernanceEvents), +/* harmony export */ getGraphEchoEvents: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getGraphEchoEvents), +/* harmony export */ getHttpAgent: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.WU), +/* harmony export */ getInstanceByAddress: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.Zh), +/* harmony export */ getMeta: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getMeta), +/* harmony export */ getNetworkConfig: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.RY), +/* harmony export */ getNoteAccounts: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getNoteAccounts), +/* harmony export */ getProvider: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.sO), +/* harmony export */ getProviderWithNetId: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.MF), +/* harmony export */ getRegisters: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getRegisters), +/* harmony export */ getStatistic: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getStatistic), +/* harmony export */ getStatusSchema: () => (/* reexport safe */ _schemas__WEBPACK_IMPORTED_MODULE_2__.c_), +/* harmony export */ getSubdomains: () => (/* reexport safe */ _networkConfig__WEBPACK_IMPORTED_MODULE_12__.cF), +/* harmony export */ getSupportedInstances: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.XF), +/* harmony export */ getTokenBalances: () => (/* reexport safe */ _tokens__WEBPACK_IMPORTED_MODULE_18__.H), +/* harmony export */ getWeightRandom: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.c$), +/* harmony export */ getWithdrawals: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.getWithdrawals), +/* harmony export */ hexToBytes: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.aT), +/* harmony export */ isNode: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.Ll), +/* harmony export */ isRelayerUpdated: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.mU), +/* harmony export */ jobsSchema: () => (/* reexport safe */ _schemas__WEBPACK_IMPORTED_MODULE_2__.Us), +/* harmony export */ leBuff2Int: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.ae), +/* harmony export */ leInt2Buff: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.EI), +/* harmony export */ loadCachedEvents: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.sw), +/* harmony export */ loadSavedEvents: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.rx), +/* harmony export */ mimc: () => (/* reexport safe */ _mimc__WEBPACK_IMPORTED_MODULE_10__.f), +/* harmony export */ multicall: () => (/* reexport safe */ _multicall__WEBPACK_IMPORTED_MODULE_11__.C), +/* harmony export */ packEncryptedMessage: () => (/* reexport safe */ _encryptedNotes__WEBPACK_IMPORTED_MODULE_7__.Fr), +/* harmony export */ parseAddress: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.or), +/* harmony export */ parseKey: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.Do), +/* harmony export */ parseMnemonic: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.qc), +/* harmony export */ parseNumber: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.$J), +/* harmony export */ parseRecoveryKey: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__._p), +/* harmony export */ parseRelayer: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.yJ), +/* harmony export */ parseSemanticVersion: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.qo), +/* harmony export */ parseUrl: () => (/* reexport safe */ _parser__WEBPACK_IMPORTED_MODULE_13__.Dl), +/* harmony export */ pedersen: () => (/* reexport safe */ _pedersen__WEBPACK_IMPORTED_MODULE_14__.NO), +/* harmony export */ pickWeightedRandomRelayer: () => (/* reexport safe */ _relayerClient__WEBPACK_IMPORTED_MODULE_17__.sN), +/* harmony export */ populateTransaction: () => (/* reexport safe */ _providers__WEBPACK_IMPORTED_MODULE_16__.zr), +/* harmony export */ queryGraph: () => (/* reexport safe */ _graphql__WEBPACK_IMPORTED_MODULE_1__.queryGraph), +/* harmony export */ rBigInt: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.ib), +/* harmony export */ saveUserFile: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.jj), +/* harmony export */ sleep: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.yy), +/* harmony export */ substring: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.uU), +/* harmony export */ toFixedHex: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.$W), +/* harmony export */ toFixedLength: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.sY), +/* harmony export */ unpackEncryptedMessage: () => (/* reexport safe */ _encryptedNotes__WEBPACK_IMPORTED_MODULE_7__.ol), +/* harmony export */ unzipAsync: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.fY), +/* harmony export */ validateUrl: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_20__.wv), +/* harmony export */ zipAsync: () => (/* reexport safe */ _data__WEBPACK_IMPORTED_MODULE_5__.a8) +/* harmony export */ }); +/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94513); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _events__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== "default") __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _events__WEBPACK_IMPORTED_MODULE_0__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _graphql__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(52049); +/* harmony import */ var _schemas__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7613); +/* harmony import */ var _typechain__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(67276); +/* harmony import */ var _batch__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9723); +/* harmony import */ var _data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(11489); +/* harmony import */ var _deposits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7240); +/* harmony import */ var _encryptedNotes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33298); +/* harmony import */ var _fees__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(37182); +/* harmony import */ var _merkleTree__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(5217); +/* harmony import */ var _mimc__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(22901); +/* harmony import */ var _multicall__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(48486); +/* harmony import */ var _networkConfig__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(59499); +/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(30200); +/* harmony import */ var _pedersen__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(85111); +/* harmony import */ var _prices__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(34525); +/* harmony import */ var _providers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(64819); +/* harmony import */ var _relayerClient__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(57194); +/* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(7393); +/* harmony import */ var _treeCache__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(15609); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(67418); +/* harmony import */ var _websnark__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(26746); + + + + + + + + + + + + + + + + + + + + + + + + +})(); + +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/dist/merkleTree.d.ts b/dist/merkleTree.d.ts new file mode 100644 index 0000000..663ba99 --- /dev/null +++ b/dist/merkleTree.d.ts @@ -0,0 +1,30 @@ +import { MerkleTree, PartialMerkleTree, Element, TreeEdge } from '@tornado/fixed-merkle-tree'; +import type { Tornado } from '@tornado/contracts'; +import type { DepositType } from './deposits'; +import type { DepositsEvents } from './events'; +import type { NetIdType } from './networkConfig'; +export type MerkleTreeConstructor = DepositType & { + Tornado: Tornado; + commitmentHex?: string; + merkleTreeHeight?: number; + emptyElement?: string; + merkleWorkerPath?: string; +}; +export declare class MerkleTreeService { + currency: string; + amount: string; + netId: NetIdType; + Tornado: Tornado; + commitmentHex?: string; + instanceName: string; + merkleTreeHeight: number; + emptyElement: string; + merkleWorkerPath?: string; + constructor({ netId, amount, currency, Tornado, commitmentHex, merkleTreeHeight, emptyElement, merkleWorkerPath, }: MerkleTreeConstructor); + createTree(events: Element[]): Promise; + createPartialTree({ edge, elements }: { + edge: TreeEdge; + elements: Element[]; + }): Promise; + verifyTree(events: DepositsEvents[]): Promise; +} diff --git a/dist/merkleTreeWorker.d.ts b/dist/merkleTreeWorker.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/merkleTreeWorker.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/merkleTreeWorker.js b/dist/merkleTreeWorker.js new file mode 100644 index 0000000..835b909 --- /dev/null +++ b/dist/merkleTreeWorker.js @@ -0,0 +1,19828 @@ +'use strict'; + +var threads = require('worker_threads'); +var crypto = require('crypto'); +var os = require('os'); +var URL = require('url'); +var VM = require('vm'); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var lib = {}; + +var FixedMerkleTree = {}; + +var simpleHash$1 = {}; + +Object.defineProperty(simpleHash$1, "__esModule", { value: true }); +simpleHash$1.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +simpleHash$1.simpleHash = simpleHash; +simpleHash$1.default = (left, right) => simpleHash([left, right]); + +var BaseTree$1 = {}; + +Object.defineProperty(BaseTree$1, "__esModule", { value: true }); +BaseTree$1.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} +BaseTree$1.BaseTree = BaseTree; + +var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(FixedMerkleTree, "__esModule", { value: true }); +const simpleHash_1$1 = __importDefault$1(simpleHash$1); +const BaseTree_1$1 = BaseTree$1; +class MerkleTree extends BaseTree_1$1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1$1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1$1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1$1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +FixedMerkleTree.default = MerkleTree; + +var PartialMerkleTree$1 = {}; + +var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(PartialMerkleTree$1, "__esModule", { value: true }); +PartialMerkleTree$1.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(simpleHash$1); +const BaseTree_1 = BaseTree$1; +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +PartialMerkleTree$1.PartialMerkleTree = PartialMerkleTree; + +(function (exports) { + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; + const FixedMerkleTree_1 = __importDefault(FixedMerkleTree); + Object.defineProperty(exports, "MerkleTree", { enumerable: true, get: function () { return FixedMerkleTree_1.default; } }); + var PartialMerkleTree_1 = PartialMerkleTree$1; + Object.defineProperty(exports, "PartialMerkleTree", { enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } }); + var simpleHash_1 = simpleHash$1; + Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return simpleHash_1.simpleHash; } }); + exports.default = FixedMerkleTree_1.default; +} (lib)); + +/* global BigInt */ +const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; + +function fromString$2(s, radix) { + if ((!radix)||(radix==10)) { + return BigInt(s); + } else if (radix==16) { + if (s.slice(0,2) == "0x") { + return BigInt(s); + } else { + return BigInt("0x"+s); + } + } +} + +const e$2 = fromString$2; + +function fromArray$2(a, radix) { + let acc =BigInt(0); + radix = BigInt(radix); + for (let i=0; i> BigInt(n); +} + +const shl$2 = shiftLeft$2; +const shr$2 = shiftRight$2; + +function isOdd$2(a) { + return (BigInt(a) & BigInt(1)) == BigInt(1); +} + + +function naf$2(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + const z = 2 - Number(E % BigInt(4)); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + + +function bits$2(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + res.push(1); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + +function toNumber$3(s) { + if (s>BigInt(Number.MAX_SAFE_INTEGER )) { + throw new Error("Number too big"); + } + return Number(s); +} + +function toArray$2(s, radix) { + const res = []; + let rem = BigInt(s); + radix = BigInt(radix); + while (rem) { + res.unshift( Number(rem % radix)); + rem = rem / radix; + } + return res; +} + + +function add$2(a, b) { + return BigInt(a) + BigInt(b); +} + +function sub$2(a, b) { + return BigInt(a) - BigInt(b); +} + +function neg$2(a) { + return -BigInt(a); +} + +function mul$2(a, b) { + return BigInt(a) * BigInt(b); +} + +function square$2(a) { + return BigInt(a) * BigInt(a); +} + +function pow$2(a, b) { + return BigInt(a) ** BigInt(b); +} + +function exp$2(a, b) { + return BigInt(a) ** BigInt(b); +} + +function abs$2(a) { + return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); +} + +function div$2(a, b) { + return BigInt(a) / BigInt(b); +} + +function mod$2(a, b) { + return BigInt(a) % BigInt(b); +} + +function eq$2(a, b) { + return BigInt(a) == BigInt(b); +} + +function neq$2(a, b) { + return BigInt(a) != BigInt(b); +} + +function lt$2(a, b) { + return BigInt(a) < BigInt(b); +} + +function gt$2(a, b) { + return BigInt(a) > BigInt(b); +} + +function leq$2(a, b) { + return BigInt(a) <= BigInt(b); +} + +function geq$2(a, b) { + return BigInt(a) >= BigInt(b); +} + +function band$2(a, b) { + return BigInt(a) & BigInt(b); +} + +function bor$2(a, b) { + return BigInt(a) | BigInt(b); +} + +function bxor$2(a, b) { + return BigInt(a) ^ BigInt(b); +} + +function land$2(a, b) { + return BigInt(a) && BigInt(b); +} + +function lor$2(a, b) { + return BigInt(a) || BigInt(b); +} + +function lnot$2(a) { + return !BigInt(a); +} + +var Scalar_native = /*#__PURE__*/Object.freeze({ + __proto__: null, + abs: abs$2, + add: add$2, + band: band$2, + bitLength: bitLength$2, + bits: bits$2, + bor: bor$2, + bxor: bxor$2, + div: div$2, + e: e$2, + eq: eq$2, + exp: exp$2, + fromArray: fromArray$2, + fromString: fromString$2, + geq: geq$2, + gt: gt$2, + isNegative: isNegative$2, + isOdd: isOdd$2, + isZero: isZero$2, + land: land$2, + leq: leq$2, + lnot: lnot$2, + lor: lor$2, + lt: lt$2, + mod: mod$2, + mul: mul$2, + naf: naf$2, + neg: neg$2, + neq: neq$2, + pow: pow$2, + shiftLeft: shiftLeft$2, + shiftRight: shiftRight$2, + shl: shl$2, + shr: shr$2, + square: square$2, + sub: sub$2, + toArray: toArray$2, + toNumber: toNumber$3 +}); + +var BigInteger = {exports: {}}; + +(function (module) { + var bigInt = (function (undefined$1) { + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + }; + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + }; + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + }; + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + }; + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + }; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + }; + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + }; + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var t = iterations === undefined$1 ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + }; + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + }; + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }; + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + }; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; + })(); + + // Node.js check + if (module.hasOwnProperty("exports")) { + module.exports = bigInt; + } +} (BigInteger)); + +var BigIntegerExports = BigInteger.exports; +var bigInt$8 = /*@__PURE__*/getDefaultExportFromCjs(BigIntegerExports); + +function fromString$1(s, radix) { + if (typeof s == "string") { + if (s.slice(0,2) == "0x") { + return bigInt$8(s.slice(2), 16); + } else { + return bigInt$8(s,radix); + } + } else { + return bigInt$8(s, radix); + } +} + +const e$1 = fromString$1; + +function fromArray$1(a, radix) { + return bigInt$8.fromArray(a, radix); +} + +function bitLength$1(a) { + return bigInt$8(a).bitLength(); +} + +function isNegative$1(a) { + return bigInt$8(a).isNegative(); +} + +function isZero$1(a) { + return bigInt$8(a).isZero(); +} + +function shiftLeft$1(a, n) { + return bigInt$8(a).shiftLeft(n); +} + +function shiftRight$1(a, n) { + return bigInt$8(a).shiftRight(n); +} + +const shl$1 = shiftLeft$1; +const shr$1 = shiftRight$1; + +function isOdd$1(a) { + return bigInt$8(a).isOdd(); +} + + +function naf$1(n) { + let E = bigInt$8(n); + const res = []; + while (E.gt(bigInt$8.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function bits$1(n) { + let E = bigInt$8(n); + const res = []; + while (E.gt(bigInt$8.zero)) { + if (E.isOdd()) { + res.push(1); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function toNumber$2(s) { + if (!s.lt(bigInt$8("9007199254740992", 10))) { + throw new Error("Number too big"); + } + return s.toJSNumber(); +} + +function toArray$1(s, radix) { + return bigInt$8(s).toArray(radix); +} + +function add$1(a, b) { + return bigInt$8(a).add(bigInt$8(b)); +} + +function sub$1(a, b) { + return bigInt$8(a).minus(bigInt$8(b)); +} + +function neg$1(a) { + return bigInt$8.zero.minus(bigInt$8(a)); +} + +function mul$1(a, b) { + return bigInt$8(a).times(bigInt$8(b)); +} + +function square$1(a) { + return bigInt$8(a).square(); +} + +function pow$1(a, b) { + return bigInt$8(a).pow(bigInt$8(b)); +} + +function exp$1(a, b) { + return bigInt$8(a).pow(bigInt$8(b)); +} + +function abs$1(a) { + return bigInt$8(a).abs(); +} + +function div$1(a, b) { + return bigInt$8(a).divide(bigInt$8(b)); +} + +function mod$1(a, b) { + return bigInt$8(a).mod(bigInt$8(b)); +} + +function eq$1(a, b) { + return bigInt$8(a).eq(bigInt$8(b)); +} + +function neq$1(a, b) { + return bigInt$8(a).neq(bigInt$8(b)); +} + +function lt$1(a, b) { + return bigInt$8(a).lt(bigInt$8(b)); +} + +function gt$1(a, b) { + return bigInt$8(a).gt(bigInt$8(b)); +} + +function leq$1(a, b) { + return bigInt$8(a).leq(bigInt$8(b)); +} + +function geq$1(a, b) { + return bigInt$8(a).geq(bigInt$8(b)); +} + +function band$1(a, b) { + return bigInt$8(a).and(bigInt$8(b)); +} + +function bor$1(a, b) { + return bigInt$8(a).or(bigInt$8(b)); +} + +function bxor$1(a, b) { + return bigInt$8(a).xor(bigInt$8(b)); +} + +function land$1(a, b) { + return (!bigInt$8(a).isZero()) && (!bigInt$8(b).isZero()); +} + +function lor$1(a, b) { + return (!bigInt$8(a).isZero()) || (!bigInt$8(b).isZero()); +} + +function lnot$1(a) { + return bigInt$8(a).isZero(); +} + +var Scalar_bigint = /*#__PURE__*/Object.freeze({ + __proto__: null, + abs: abs$1, + add: add$1, + band: band$1, + bitLength: bitLength$1, + bits: bits$1, + bor: bor$1, + bxor: bxor$1, + div: div$1, + e: e$1, + eq: eq$1, + exp: exp$1, + fromArray: fromArray$1, + fromString: fromString$1, + geq: geq$1, + gt: gt$1, + isNegative: isNegative$1, + isOdd: isOdd$1, + isZero: isZero$1, + land: land$1, + leq: leq$1, + lnot: lnot$1, + lor: lor$1, + lt: lt$1, + mod: mod$1, + mul: mul$1, + naf: naf$1, + neg: neg$1, + neq: neq$1, + pow: pow$1, + shiftLeft: shiftLeft$1, + shiftRight: shiftRight$1, + shl: shl$1, + shr: shr$1, + square: square$1, + sub: sub$1, + toArray: toArray$1, + toNumber: toNumber$2 +}); + +const supportsNativeBigInt$1 = typeof BigInt === "function"; + +let Scalar$1 = {}; +if (supportsNativeBigInt$1) { + Object.assign(Scalar$1, Scalar_native); +} else { + Object.assign(Scalar$1, Scalar_bigint); +} + + +// Returns a buffer with Little Endian Representation +Scalar$1.toRprLE = function rprBE(buff, o, e, n8) { + const s = "0000000" + e.toString(16); + const v = new Uint32Array(buff.buffer, o, n8/4); + const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; + for (let i=0; i> 5)+1; // Number of 32bit words; + for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); + return Scalar$1.fromString(a.join(""), 16); +}; + +// Pases a buffer with Big Endian Representation +Scalar$1.fromRprBE = function rprLEM(buff, o, n8) { + n8 = n8 || buff.byteLength; + o = o || 0; + const v = new DataView(buff.buffer, buff.byteOffset + o, n8); + const a = new Array(n8/4); + for (let i=0; i>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; + + st[a] = (st[a] + st[b]) >>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; +} + +function doubleRound(st) { + quarterRound(st, 0, 4, 8,12); + quarterRound(st, 1, 5, 9,13); + quarterRound(st, 2, 6,10,14); + quarterRound(st, 3, 7,11,15); + + quarterRound(st, 0, 5,10,15); + quarterRound(st, 1, 6,11,12); + quarterRound(st, 2, 7, 8,13); + quarterRound(st, 3, 4, 9,14); +} + +class ChaCha { + + constructor(seed) { + seed = seed || [0,0,0,0,0,0,0,0]; + this.state = [ + 0x61707865, + 0x3320646E, + 0x79622D32, + 0x6B206574, + seed[0], + seed[1], + seed[2], + seed[3], + seed[4], + seed[5], + seed[6], + seed[7], + 0, + 0, + 0, + 0 + ]; + this.idx = 16; + this.buff = new Array(16); + } + + nextU32() { + if (this.idx == 16) this.update(); + return this.buff[this.idx++]; + } + + nextU64() { + return add(mul(this.nextU32(), 0x100000000), this.nextU32()); + } + + nextBool() { + return (this.nextU32() & 1) == 1; + } + + update() { + // Copy the state + for (let i=0; i<16; i++) this.buff[i] = this.state[i]; + + // Apply the rounds + for (let i=0; i<10; i++) doubleRound(this.buff); + + // Add to the initial + for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; + + this.idx = 0; + + this.state[12] = (this.state[12] + 1) >>> 0; + if (this.state[12] != 0) return; + this.state[13] = (this.state[13] + 1) >>> 0; + if (this.state[13] != 0) return; + this.state[14] = (this.state[14] + 1) >>> 0; + if (this.state[14] != 0) return; + this.state[15] = (this.state[15] + 1) >>> 0; + } +} + +function getRandomBytes(n) { + let array = new Uint8Array(n); + if (process.browser) { // Browser + if (typeof globalThis.crypto !== "undefined") { // Supported + globalThis.crypto.getRandomValues(array); + } else { // fallback + for (let i=0; i>>0; + } + } + } + else { // NodeJS + crypto.randomFillSync(array); + } + return array; +} + +function getRandomSeed() { + const arr = getRandomBytes(32); + const arrV = new Uint32Array(arr.buffer); + const seed = []; + for (let i=0; i<8; i++) { + seed.push(arrV[i]); + } + return seed; +} + +let threadRng = null; + +function getThreadRng() { + if (threadRng) return threadRng; + threadRng = new ChaCha(getRandomSeed()); + return threadRng; +} + +var utils$b = {}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt$7 = BigIntegerExports; + +utils$b.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = bigInt$7(_a); + for (let i=0; i. +*/ + +const utils$a = utils$b; + +var build_int = function buildInt(module, n64, _prefix) { + + const prefix = _prefix || "int"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = {}; + + const n32 = n64*2; + const n8 = n64*8; + + module.alloc(n8, utils$a.bigInt2BytesLE(1, n8)); + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("px", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + f.addCode( + c.i64_store32( + c.getLocal("r"), + k*4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4*2-4, + c.getLocal(c0_old) + ) + ); + + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function _buildMul1() { + const f = module.addFunction(prefix+"__mul1"); + f.addParam("px", "i32"); + f.addParam("y", "i64"); + f.addParam("pr", "i32"); + f.addLocal("c", "i64"); + + const c = f.getCodeBuilder(); + + f.addCode(c.setLocal( + "c", + c.i64_mul( + c.i64_load32_u(c.getLocal("px"), 0, 0), + c.getLocal("y") + ) + )); + + f.addCode(c.i64_store32( + c.getLocal("pr"), + 0, + 0, + c.getLocal("c"), + )); + + for (let i=1; i3)&&(Y[eY]==0) ey--; + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(Y , c.getLocal("eY")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eY"), + c.i32_const(3) + ) + ) + ), + c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), + c.br(0) + ))); + + f.addCode( + c.setLocal( + "sy", + c.i64_add( + c.i64_load32_u( + c.i32_sub( + c.i32_add( Y, c.getLocal("eY")), + c.i32_const(3) + ), + 0, + 0 + ), + c.i64_const(1) + ) + ) + ); + + // Force a divide by 0 if quotien is 0 + f.addCode( + c.if( + c.i64_eq( + c.getLocal("sy"), + c.i64_const(1) + ), + c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) + ) + ); + + f.addCode(c.block(c.loop( + + // while (eX>7)&&(Y[eX]==0) ex--; + c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(R , c.getLocal("eX")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eX"), + c.i32_const(7) + ) + ) + ), + c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal( + "sx", + c.i64_load( + c.i32_sub( + c.i32_add( R, c.getLocal("eX")), + c.i32_const(7) + ), + 0, + 0 + ) + ), + + c.setLocal( + "sx", + c.i64_div_u( + c.getLocal("sx"), + c.getLocal("sy") + ) + ), + c.setLocal( + "ec", + c.i32_sub( + c.i32_sub( + c.getLocal("eX"), + c.getLocal("eY") + ), + c.i32_const(4) + ) + ), + + // While greater than 32 bits or ec is neg, shr and inc exp + c.block(c.loop( + c.br_if( + 1, + c.i32_and( + c.i64_eqz( + c.i64_and( + c.getLocal("sx"), + c.i64_const("0xFFFFFFFF00000000") + ) + ), + c.i32_ge_s( + c.getLocal("ec"), + c.i32_const(0) + ) + ) + ), + + c.setLocal( + "sx", + c.i64_shr_u( + c.getLocal("sx"), + c.i64_const(8) + ) + ), + + c.setLocal( + "ec", + c.i32_add( + c.getLocal("ec"), + c.i32_const(1) + ) + ), + c.br(0) + )), + + c.if( + c.i64_eqz(c.getLocal("sx")), + [ + ...c.br_if( + 2, + c.i32_eqz(c.call(prefix + "_gte", R, Y)) + ), + ...c.setLocal("sx", c.i64_const(1)), + ...c.setLocal("ec", c.i32_const(0)) + ] + ), + + c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), + c.drop(c.call( + prefix + "_sub", + R, + c.i32_sub(R2, c.getLocal("ec")), + R + )), + c.call( + prefix + "__add1", + c.i32_add(C, c.getLocal("ec")), + c.getLocal("sx") + ), + c.br(0) + ))); + } + + function buildInverseMod() { + + const f = module.addFunction(prefix+"_inverseMod"); + f.addParam("px", "i32"); + f.addParam("pm", "i32"); + f.addParam("pr", "i32"); + f.addLocal("t", "i32"); + f.addLocal("newt", "i32"); + f.addLocal("r", "i32"); + f.addLocal("qq", "i32"); + f.addLocal("qr", "i32"); + f.addLocal("newr", "i32"); + f.addLocal("swp", "i32"); + f.addLocal("x", "i32"); + f.addLocal("signt", "i32"); + f.addLocal("signnewt", "i32"); + f.addLocal("signx", "i32"); + + const c = f.getCodeBuilder(); + + const aux1 = c.i32_const(module.alloc(n8)); + const aux2 = c.i32_const(module.alloc(n8)); + const aux3 = c.i32_const(module.alloc(n8)); + const aux4 = c.i32_const(module.alloc(n8)); + const aux5 = c.i32_const(module.alloc(n8)); + const aux6 = c.i32_const(module.alloc(n8)); + const mulBuff = c.i32_const(module.alloc(n8*2)); + const aux7 = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("t", aux1), + c.call(prefix + "_zero", aux1), + c.setLocal("signt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("r", aux2), + c.call(prefix + "_copy", c.getLocal("pm"), aux2) + ); + + f.addCode( + c.setLocal("newt", aux3), + c.call(prefix + "_one", aux3), + c.setLocal("signnewt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("newr", aux4), + c.call(prefix + "_copy", c.getLocal("px"), aux4) + ); + + + + + f.addCode(c.setLocal("qq", aux5)); + f.addCode(c.setLocal("qr", aux6)); + f.addCode(c.setLocal("x", aux7)); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.call(prefix + "_isZero", c.getLocal("newr") ) + ), + c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), + + c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), + + c.if( + c.getLocal("signt"), + c.if( + c.getLocal("signnewt"), + c.if ( + c.call(prefix + "_gte", mulBuff, c.getLocal("t")), + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ], + ), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ), + c.if( + c.getLocal("signnewt"), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + c.if ( + c.call(prefix + "_gte", c.getLocal("t"), mulBuff), + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ) + ) + ), + + c.setLocal("swp", c.getLocal("t")), + c.setLocal("t", c.getLocal("newt")), + c.setLocal("newt", c.getLocal("x")), + c.setLocal("x", c.getLocal("swp")), + + c.setLocal("signt", c.getLocal("signnewt")), + c.setLocal("signnewt", c.getLocal("signx")), + + c.setLocal("swp", c.getLocal("r")), + c.setLocal("r", c.getLocal("newr")), + c.setLocal("newr", c.getLocal("qr")), + c.setLocal("qr", c.getLocal("swp")), + + c.br(0) + ))); + + f.addCode(c.if( + c.getLocal("signt"), + c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), + c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) + )); + } + + + buildCopy(); + buildZero(); + buildIsZero(); + buildOne(); + buildEq(); + buildGte(); + buildAdd(); + buildSub(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildDiv(); + buildInverseMod(); + module.exportFunction(prefix+"_copy"); + module.exportFunction(prefix+"_zero"); + module.exportFunction(prefix+"_one"); + module.exportFunction(prefix+"_isZero"); + module.exportFunction(prefix+"_eq"); + module.exportFunction(prefix+"_gte"); + module.exportFunction(prefix+"_add"); + module.exportFunction(prefix+"_sub"); + module.exportFunction(prefix+"_mul"); + module.exportFunction(prefix+"_square"); + module.exportFunction(prefix+"_squareOld"); + module.exportFunction(prefix+"_div"); + module.exportFunction(prefix+"_inverseMod"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_timesscalar = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("i", "i32"); + f.addLocal("b", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ) + ); + f.addCode(c.call(opCopy, c.getLocal("base"), aux)); + f.addCode(c.call(opInit, c.getLocal("r"))); + f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); + f.addCode(c.block(c.loop( + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + + c.setLocal( + "b", + c.i32_load8_u( + c.i32_add( + c.getLocal("scalar"), + c.getLocal("i") + ) + ) + ), + ...innerLoop(), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.br(0) + ))); + + + function innerLoop() { + const code = []; + for (let i=0; i<8; i++) { + code.push( + ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), + ...c.if( + c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), + [ + ...c.setLocal( + "b", + c.i32_sub( + c.getLocal("b"), + c.i32_const(0x80 >> i) + ) + ), + ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) + ] + ) + ); + } + return code; + } + +}; + +var build_batchinverse = buildBatchInverse$3; + +function buildBatchInverse$3(module, prefix) { + + + const n8 = module.modules[prefix].n64*8; + + const f = module.addFunction(prefix+"_batchInverse"); + f.addParam("pIn", "i32"); + f.addParam("inStep", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addParam("outStep", "i32"); + f.addLocal("itAux", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut","i32"); + f.addLocal("i","i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + + // Alloc Working space for accumulated umltiplications + f.addCode( + c.setLocal("itAux", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("itAux"), + c.i32_mul( + c.i32_add( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(n8) + ) + ) + ) + ); + + f.addCode( + + // aux[0] = a; + c.call(prefix+"_one", c.getLocal("itAux")), + // for (i=0;i. +*/ + +const bigInt$6 = BigIntegerExports; +const buildInt = build_int; +const utils$9 = utils$b; +const buildExp$2 = build_timesscalar; +const buildBatchInverse$2 = build_batchinverse; +const buildBatchConvertion$1 = build_batchconvertion; +const buildBatchOp = build_batchop; + +var build_f1m = function buildF1m(module, _q, _prefix, _intPrefix) { + const q = bigInt$6(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n32 = n64*2; + const n8 = n64*8; + + const prefix = _prefix || "f1m"; + if (module.modules[prefix]) return prefix; // already builded + + const intPrefix = buildInt(module, n64, _intPrefix); + const pq = module.alloc(n8, utils$9.bigInt2BytesLE(q, n8)); + + module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).mod(q), n8)); + const pR2 = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).square().mod(q), n8)); + const pOne = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.one.shiftLeft(n64*64).mod(q), n8)); + const pZero = module.alloc(utils$9.bigInt2BytesLE(bigInt$6.zero, n8)); + const _minusOne = q.minus(bigInt$6.one); + const _e = _minusOne.shiftRight(1); // e = (p-1)/2 + const pe = module.alloc(n8, utils$9.bigInt2BytesLE(_e, n8)); + + const _ePlusOne = _e.add(bigInt$6.one); // e = (p-1)/2 + const pePlusOne = module.alloc(n8, utils$9.bigInt2BytesLE(_ePlusOne, n8)); + + module.modules[prefix] = { + pq: pq, + pR2: pR2, + n64: n64, + q: q, + pOne: pOne, + pZero: pZero, + pePlusOne: pePlusOne + }; + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); + } + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) + ) + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) + ); + } + + +/* + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.i32_and( + c.i32_load(AUX), + c.i32_const(1) + ) + ); + } +*/ + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if ( + c.call(intPrefix + "_isZero", c.getLocal("x")), + c.ret(c.i32_const(0)) + ), + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.if( + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), + c.ret(c.i32_const(-1)) + ), + c.ret(c.i32_const(1)) + ); + } + + + function buildMReduct() { + const carries = module.alloc(n32*n32*8); + + const f = module.addFunction(prefix+"_mReduct"); + f.addParam("t", "i32"); + f.addParam("r", "i32"); + f.addLocal("np32", "i64"); + f.addLocal("c", "i64"); + f.addLocal("m", "i64"); + + const c = f.getCodeBuilder(); + + const np32 = bigInt$6("100000000",16).minus( q.modInv(bigInt$6("100000000",16))).toJSNumber(); + + f.addCode(c.setLocal("np32", c.i64_const(np32))); + + for (let i=0; i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + [c0, c1] = [c1, c0]; + f.addCode( + c.setLocal(c1, + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquare() { + + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("c0", "i64"); + f.addLocal("c1", "i64"); + f.addLocal("c0_old", "i64"); + f.addLocal("c1_old", "i64"); + f.addLocal("np32", "i64"); + + + for (let i=0;i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + + for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0_old) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1_old)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildFromMontgomery() { + + const pAux2 = module.alloc(n8*2); + + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); + f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); + f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); + } + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); + f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); + } + + // Calculate various valuse needed for sqrt + + + let _nqr = bigInt$6(2); + if (q.isPrime()) { + while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt$6.one); + } + + module.alloc(utils$9.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); + + let s2 = 0; + let _t = _minusOne; + + while ((!_t.isOdd())&&(!_t.isZero())) { + s2++; + _t = _t.shiftRight(1); + } + const pt = module.alloc(n8, utils$9.bigInt2BytesLE(_t, n8)); + + const _nqrToT = _nqr.modPow(_t, q); + const pNqrToT = module.alloc(utils$9.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); + + const _tPlusOneOver2 = _t.add(1).shiftRight(1); + const ptPlusOneOver2 = module.alloc(n8, utils$9.bigInt2BytesLE(_tPlusOneOver2, n8)); + + function buildSqrt() { + + const f = module.addFunction(prefix+ "_sqrt"); + f.addParam("n", "i32"); + f.addParam("r", "i32"); + f.addLocal("m", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const C = c.i32_const(module.alloc(n8)); + const T = c.i32_const(module.alloc(n8)); + const R = c.i32_const(module.alloc(n8)); + const SQ = c.i32_const(module.alloc(n8)); + const B = c.i32_const(module.alloc(n8)); + + f.addCode( + + // If (n==0) return 0 + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret( + c.call(prefix + "_zero", c.getLocal("r")) + ) + ), + + c.setLocal("m", c.i32_const(s2)), + c.call(prefix + "_copy", c.i32_const(pNqrToT), C), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), + + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", T, ONE)), + + c.call(prefix + "_square", T, SQ), + c.setLocal("i", c.i32_const(1)), + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), + c.call(prefix + "_square", SQ, SQ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_copy", C, B), + c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("j"))), + c.call(prefix + "_square", B, B), + c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("m", c.getLocal("i")), + c.call(prefix + "_square", B, C), + c.call(prefix + "_mul", T, C, T), + c.call(prefix + "_mul", R, B, R), + + c.br(0) + )), + + c.if( + c.call(prefix + "_isNegative", R), + c.call(prefix + "_neg", R, c.getLocal("r")), + c.call(prefix + "_copy", R, c.getLocal("r")), + ) + ); + } + + function buildIsSquare() { + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret(c.i32_const(1)) + ), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), + c.call(prefix + "_eq", AUX, ONE) + ); + } + + + function buildLoad() { + const f = module.addFunction(prefix+"_load"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + f.addLocal("p", "i32"); + f.addLocal("l", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + const c = f.getCodeBuilder(); + + const R = c.i32_const(module.alloc(n8)); + const pAux = module.alloc(n8); + const AUX = c.i32_const(pAux); + + f.addCode( + c.call(intPrefix + "_zero", c.getLocal("r")), + c.setLocal("i", c.i32_const(n8)), + c.setLocal("p", c.getLocal("scalar")), + c.block(c.loop( + c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", c.getLocal("p"), R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), + c.br(0) + )), + + c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), + c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), + c.call(intPrefix + "_zero", AUX), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), + + c.i32_store8( + c.getLocal("j"), + pAux, + c.i32_load8_u(c.getLocal("p")), + ), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", AUX, R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), + c.call(prefix + "_toMontgomery", AUX, AUX), + c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + f.addCode( + c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) + ); + } + + + module.exportFunction(intPrefix + "_copy", prefix+"_copy"); + module.exportFunction(intPrefix + "_zero", prefix+"_zero"); + module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(intPrefix + "_eq", prefix+"_eq"); + + buildIsOne(); + buildAdd(); + buildSub(); + buildNeg(); + buildMReduct(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildToMontgomery(); + buildFromMontgomery(); + buildIsNegative(); + buildSign(); + buildInverse(); + buildOne(); + buildLoad(); + buildTimesScalar(); + buildBatchInverse$2(module, prefix); + buildBatchConvertion$1(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); + buildBatchConvertion$1(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); + buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); + buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); + buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); + + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_mReduct"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_squareOld"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_load"); + module.exportFunction(prefix + "_timesScalar"); + buildExp$2( + module, + prefix + "_exp", + n8, + prefix + "_mul", + prefix + "_square", + intPrefix + "_copy", + prefix + "_one", + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_batchInverse"); + if (q.isPrime()) { + buildSqrt(); + buildIsSquare(); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + } + module.exportFunction(prefix + "_batchToMontgomery"); + module.exportFunction(prefix + "_batchFromMontgomery"); + // console.log(module.functionIdxByName); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt$5 = BigIntegerExports; + +const buildF1m$2 =build_f1m; + +var build_f1 = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { + + const q = bigInt$5(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + + const prefix = _prefix || "f1"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64 + }; + + const intPrefix = _intPrefix || "int"; + const f1mPrefix = buildF1m$2(module, q, _f1mPrefix, intPrefix); + + + const pR2 = module.modules[f1mPrefix].pR2; + const pq = module.modules[f1mPrefix].pq; + const pePlusOne = module.modules[f1mPrefix].pePlusOne; + + function buildMul() { + const pAux1 = module.alloc(n8); + + const f = module.addFunction(prefix+ "_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); + f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) + ); + } + + + buildMul(); + buildSquare(); + buildInverse(); + buildIsNegative(); + module.exportFunction(f1mPrefix + "_add", prefix + "_add"); + module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); + module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); + module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); + module.exportFunction(f1mPrefix + "_one", prefix+"_one"); + module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp$1 = build_timesscalar; +const buildBatchInverse$1 = build_batchinverse; +const bigInt$4 = BigIntegerExports; +const utils$8 = utils$b; + +var build_f2m = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + const q = module.modules[f1mPrefix].q; + + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*2 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + function buildConjugate() { + const f = module.addFunction(prefix+"_conjugate"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ); + } + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const A = c.i32_const(module.alloc(f1n8)); + const B = c.i32_const(module.alloc(f1n8)); + const C = c.i32_const(module.alloc(f1n8)); + const D = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 + c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 + + c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 + c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 + c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 + + // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) + c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) + c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) + c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 + c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 + ); + + } + + function buildMul1() { + const f = module.addFunction(prefix+"_mul1"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y = c.getLocal("y"); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y + c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y + ); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const AB = c.i32_const(module.alloc(f1n8)); + const APB = c.i32_const(module.alloc(f1n8)); + const APNB = c.i32_const(module.alloc(f1n8)); + const ABPNAB = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + // AB = x0*y1 + c.call(f1mPrefix + "_mul", x0, x1, AB), + + // APB = x0+y1 + c.call(f1mPrefix + "_add", x0, x1, APB), + + // APBN0 = x0 + nr*x1 + c.call(mulNonResidueFn, x1, APNB), + c.call(f1mPrefix + "_add", x0, APNB, APNB), + + // ABPNAB = ab + nr*ab + c.call(mulNonResidueFn, AB, ABPNAB), + c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), + + // r0 = APB * APNB - ABPNAB + c.call(f1mPrefix + "_mul", APB, APNB, r0), + c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), + + // r1 = AB + AB + c.call(f1mPrefix + "_add", AB, AB, r1), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1) + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), + c.call(mulNonResidueFn, t1, t2), + + c.call(f1mPrefix+"_sub", t0, t2, t2), + c.call(f1mPrefix+"_inverse", t2, t3), + + c.call(f1mPrefix+"_mul", x0, t3, r0), + c.call(f1mPrefix+"_mul", x1, t3, r1), + c.call(f1mPrefix+"_neg", r1, r1), + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.ret(c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1), + )) + ); + } + + + // Check here: https://eprint.iacr.org/2012/685.pdf + // Alg 9adj + function buildSqrt() { + + const f = module.addFunction(prefix+"_sqrt"); + f.addParam("a", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(3)).divide(4), f1n8 ))); + const e12 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(1)).divide(2), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + const n1a = c.i32_const(pn1); + const n1b = c.i32_const(pn1+f1n8); + const x0 = c.i32_const(module.alloc(f1n8*2)); + const b = c.i32_const(module.alloc(f1n8*2)); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), + + // const x0 = F.mul(a1, a); + c.call(prefix + "_mul", a1, a, x0), + + // if (F.eq(alfa, F.negone)) { + c.if( + c.call(prefix + "_eq", alpha, n1), + [ + // x = F.mul(x0, [F.F.zero, F.F.one]); + ...c.call(f1mPrefix + "_zero", n1a), + ...c.call(f1mPrefix + "_one", n1b), + ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), + ], + [ + // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); + ...c.call(prefix + "_one", b), + ...c.call(prefix + "_add", b, alpha, b), + ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), + + // x = F.mul(b, x0); + ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), + ] + ) + ); + + } + + + function buildIsSquare() { + + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("a", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils$8.bigInt2BytesLE(bigInt$4(q).minus(bigInt$4(3)).divide(4), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if( + c.call( + prefix + "_eq", + a0, + n1 + ), + c.ret(c.i32_const(0)) + ), + c.ret(c.i32_const(1)) + ); + + } + + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildMul1(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildConjugate(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildSign(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_mul1"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_conjugate"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse$1(module, prefix); + buildExp$1( + module, + prefix + "_exp", + f1n8*2, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one", + ); + buildSqrt(); + buildIsSquare(); + + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + module.exportFunction(prefix + "_isNegative"); + + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildExp = build_timesscalar; +const buildBatchInverse = build_batchinverse; + +var build_f3m = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*3 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + c.call(f1mPrefix+"_add", x2, y2, r2), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), + ); + } + + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + c.call(f1mPrefix+"_sub", x2, y2, r2), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + c.call(f1mPrefix+"_neg", x2, r2), + ); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x2), + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x2)) + ); + } + + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const cd = f.getCodeBuilder(); + + const a = cd.getLocal("x"); + const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); + const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); + const A = cd.getLocal("y"); + const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); + const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); + const r0 = cd.getLocal("r"); + const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); + const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); + + const aA = cd.i32_const(module.alloc(f1n8)); + const bB = cd.i32_const(module.alloc(f1n8)); + const cC = cd.i32_const(module.alloc(f1n8)); + const a_b = cd.i32_const(module.alloc(f1n8)); + const A_B = cd.i32_const(module.alloc(f1n8)); + const a_c = cd.i32_const(module.alloc(f1n8)); + const A_C = cd.i32_const(module.alloc(f1n8)); + const b_c = cd.i32_const(module.alloc(f1n8)); + const B_C = cd.i32_const(module.alloc(f1n8)); + const aA_bB = cd.i32_const(module.alloc(f1n8)); + const aA_cC = cd.i32_const(module.alloc(f1n8)); + const bB_cC = cd.i32_const(module.alloc(f1n8)); + const AUX = cd.i32_const(module.alloc(f1n8)); + + + f.addCode( + cd.call(f1mPrefix + "_mul", a, A, aA), + cd.call(f1mPrefix + "_mul", b, B, bB), + cd.call(f1mPrefix + "_mul", c, C, cC), + + cd.call(f1mPrefix + "_add", a, b, a_b), + cd.call(f1mPrefix + "_add", A, B, A_B), + cd.call(f1mPrefix + "_add", a, c, a_c), + cd.call(f1mPrefix + "_add", A, C, A_C), + cd.call(f1mPrefix + "_add", b, c, b_c), + cd.call(f1mPrefix + "_add", B, C, B_C), + + cd.call(f1mPrefix + "_add", aA, bB, aA_bB), + cd.call(f1mPrefix + "_add", aA, cC, aA_cC), + cd.call(f1mPrefix + "_add", bB, cC, bB_cC), + + cd.call(f1mPrefix + "_mul", b_c, B_C, r0), + cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), + cd.call(mulNonResidueFn, r0, r0), + cd.call(f1mPrefix + "_add", aA, r0, r0), + + cd.call(f1mPrefix + "_mul", a_b, A_B, r1), + cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), + cd.call(mulNonResidueFn, cC, AUX), + cd.call(f1mPrefix + "_add", r1, AUX, r1), + + cd.call(f1mPrefix + "_mul", a_c, A_C, r2), + cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), + cd.call(f1mPrefix + "_add", r2, bB, r2), + ); + + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const A = c.getLocal("x"); + const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const s0 = c.i32_const(module.alloc(f1n8)); + const ab = c.i32_const(module.alloc(f1n8)); + const s1 = c.i32_const(module.alloc(f1n8)); + const s2 = c.i32_const(module.alloc(f1n8)); + const bc = c.i32_const(module.alloc(f1n8)); + const s3 = c.i32_const(module.alloc(f1n8)); + const s4 = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + + c.call(f1mPrefix + "_square", A, s0), + c.call(f1mPrefix + "_mul", A, B, ab), + c.call(f1mPrefix + "_add", ab, ab, s1), + + c.call(f1mPrefix + "_sub", A, B, s2), + c.call(f1mPrefix + "_add", s2, C, s2), + c.call(f1mPrefix + "_square", s2, s2), + + c.call(f1mPrefix + "_mul", B, C, bc), + c.call(f1mPrefix + "_add", bc, bc, s3), + + c.call(f1mPrefix + "_square", C, s4), + + c.call(mulNonResidueFn, s3, r0), + c.call(f1mPrefix + "_add", s0, r0, r0), + + c.call(mulNonResidueFn, s4, r1), + c.call(f1mPrefix + "_add", s1, r1, r1), + + c.call(f1mPrefix + "_add", s0, s4, r2), + c.call(f1mPrefix + "_sub", s3, r2, r2), + c.call(f1mPrefix + "_add", s2, r2, r2), + c.call(f1mPrefix + "_add", s1, r2, r2), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1), + c.call(f1mPrefix+"_toMontgomery", x2, r2) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1), + c.call(f1mPrefix+"_fromMontgomery", x2, r2) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1), + c.call(f1mPrefix+"_copy", x2, r2), + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1), + ), + c.call(f1mPrefix+"_eq", x2, y2) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ), + c.call(f1mPrefix+"_isZero", x2) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + const t4 = c.i32_const(module.alloc(f1n8)); + const t5 = c.i32_const(module.alloc(f1n8)); + const c0 = c.i32_const(module.alloc(f1n8)); + const c1 = c.i32_const(module.alloc(f1n8)); + const c2 = c.i32_const(module.alloc(f1n8)); + const t6 = c.i32_const(module.alloc(f1n8)); + const AUX = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + c.call(f1mPrefix+"_square", x2, t2), + c.call(f1mPrefix+"_mul", x0, x1, t3), + c.call(f1mPrefix+"_mul", x0, x2, t4), + c.call(f1mPrefix+"_mul", x1, x2, t5), + + c.call(mulNonResidueFn, t5, c0), + c.call(f1mPrefix+"_sub", t0, c0, c0), + + c.call(mulNonResidueFn, t2, c1), + c.call(f1mPrefix+"_sub", c1, t3, c1), + + c.call(f1mPrefix+"_sub", t1, t4, c2), + + c.call(f1mPrefix+"_mul", x2, c1, t6), + c.call(f1mPrefix+"_mul", x1, c2, AUX), + c.call(f1mPrefix+"_add", t6, AUX, t6), + c.call(mulNonResidueFn, t6, t6), + c.call(f1mPrefix+"_mul", x0, c0, AUX), + c.call(f1mPrefix+"_add", AUX, t6, t6), + + c.call(f1mPrefix+"_inverse", t6, t6), + + c.call(f1mPrefix+"_mul", t6, c0, r0), + c.call(f1mPrefix+"_mul", t6, c1, r1), + c.call(f1mPrefix+"_mul", t6, c2, r2) + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); + + f.addCode( + c.ret( + c.i32_and( + c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1) + ), + c.call(f1mPrefix + "_isZero", x2) + ) + ) + ); + } + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildSign(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*3, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one" + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_isNegative"); + + return prefix; +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_timesscalarnaf = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("old0", "i32"); + f.addLocal("nbits", "i32"); + f.addLocal("i", "i32"); + f.addLocal("last", "i32"); + f.addLocal("cur", "i32"); + f.addLocal("carry", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + function getBit(IDX) { + return c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("scalar"), + c.i32_and( + c.i32_shr_u( + IDX, + c.i32_const(3) + ), + c.i32_const(0xFFFFFFFC) + ) + ) + ), + c.i32_and( + IDX, + c.i32_const(0x1F) + ) + ), + c.i32_const(1) + ); + } + + function pushBit(b) { + return [ + ...c.i32_store8( + c.getLocal("p"), + c.i32_const(b) + ), + ...c.setLocal( + "p", + c.i32_add( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ]; + } + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ), + c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), + c.setLocal("old0", c.i32_load(c.i32_const(0))), + c.setLocal("p", c.getLocal("old0")), + c.i32_store( + c.i32_const(0), + c.i32_and( + c.i32_add( + c.i32_add( + c.getLocal("old0"), + c.i32_const(32) + ), + c.getLocal("nbits") + ), + c.i32_const(0xFFFFFFF8) + ) + ), + c.setLocal("i", c.i32_const(1)), + + c.setLocal("last",getBit(c.i32_const(0))), + c.setLocal("carry",c.i32_const(0)), + + c.block(c.loop( + c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + + c.setLocal("cur", getBit(c.getLocal("i"))), + c.if( c.getLocal("last"), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(1) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(1) + ], + ), + ), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.if( c.getLocal("last"), + c.if(c.getLocal("carry"), + [ + ...pushBit(255), + ...pushBit(0), + ...pushBit(1) + ] + , + [ + ...pushBit(1) + ], + ), + c.if(c.getLocal("carry"), + [ + ...pushBit(0), + ...pushBit(1) + ] + ), + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + + // p already points to the last bit + + c.call(opCopy, c.getLocal("base"), aux), + + c.call(opInit, c.getLocal("r")), + + c.block(c.loop( + + + c.call(opAA, c.getLocal("r"), c.getLocal("r")), + + + c.setLocal("cur", + c.i32_load8_u( + c.getLocal("p") + ) + ), + + c.if( + c.getLocal("cur"), + c.if( + c.i32_eq(c.getLocal("cur"), c.i32_const(1)), + c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), + c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), + ) + ), + + c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + + )), + + c.i32_store( c.i32_const(0), c.getLocal("old0")) + + ); + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_multiexp = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { + + const n64g = module.modules[prefix].n64; + const n8g = n64g*8; + + function buildGetChunk() { + const f = module.addFunction(fnName + "_getChunk"); + f.addParam("pScalar", "i32"); + f.addParam("scalarSize", "i32"); // Number of bytes of the scalar + f.addParam("startBit", "i32"); // Bit to start extract + f.addParam("chunkSize", "i32"); // Chunk size in bits + f.addLocal("bitsToEnd", "i32"); + f.addLocal("mask", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("bitsToEnd", + c.i32_sub( + c.i32_mul( + c.getLocal("scalarSize"), + c.i32_const(8) + ), + c.getLocal("startBit") + ) + ), + c.if( + c.i32_gt_s( + c.getLocal("chunkSize"), + c.getLocal("bitsToEnd") + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("bitsToEnd") + ), + c.i32_const(1) + ) + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ) + ), + c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("pScalar"), + c.i32_shr_u( + c.getLocal("startBit"), + c.i32_const(3) + ) + ), + 0, // offset + 0 // align to byte. + ), + c.i32_and( + c.getLocal("startBit"), + c.i32_const(0x7) + ) + ), + c.getLocal("mask") + ) + ); + } + + function buildMutiexpChunk() { + const f = module.addFunction(fnName + "_chunk"); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("startBit", "i32"); // bit where it starts the chunk + f.addParam("chunkSize", "i32"); // bit where it starts the chunk + f.addParam("pr", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("n")), + [ + ...c.call(prefix + "_zero", c.getLocal("pr")), + ...c.ret([]) + ] + ), + + // Allocate memory + + c.setLocal( + "nTable", + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ) + ), + c.setLocal("pTable", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("nTable"), + c.i32_const(n8g) + ) + ) + ), + + // Reset Table + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nTable") + ) + ), + + c.call( + prefix + "_zero", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("j"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + // Distribute elements + c.setLocal("itBase", c.getLocal("pBases")), + c.setLocal("itScalar", c.getLocal("pScalars")), + c.setLocal("endScalar", + c.i32_add( + c.getLocal("pScalars"), + c.i32_mul( + c.getLocal("n"), + c.getLocal("scalarSize") + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("itScalar"), + c.getLocal("endScalar") + ) + ), + + c.setLocal( + "idx", + c.call(fnName + "_getChunk", + c.getLocal("itScalar"), + c.getLocal("scalarSize"), + c.getLocal("startBit"), + c.getLocal("chunkSize") + ) + ), + + c.if( + c.getLocal("idx"), + [ + ...c.setLocal( + "pIdxTable", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.i32_sub( + c.getLocal("idx"), + c.i32_const(1) + ), + c.i32_const(n8g) + ) + ) + ), + ...c.call( + opAdd, + c.getLocal("pIdxTable"), + c.getLocal("itBase"), + c.getLocal("pIdxTable"), + ) + ] + ), + + c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), + c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), + c.br(0) + )), + + c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), + c.call( + prefix + "_copy", + c.getLocal("pTable"), + c.getLocal("pr") + ), + + + c.i32_store( + c.i32_const(0), + c.getLocal("pTable") + ) + + ); + } + + function buildMultiexp() { + const f = module.addFunction(fnName); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("pr", "i32"); + f.addLocal("chunkSize", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("itBit", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8g)); + + const pTSizes = module.alloc([ + 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 16, 16, 15, 14, 13, 13, + 12, 11, 10, 9, 8, 7, 7, 6, + 5 , 4, 3, 2, 1, 1, 1, 1 + ]); + + f.addCode( + c.call(prefix + "_zero", c.getLocal("pr")), + c.if( + c.i32_eqz(c.getLocal("n")), + c.ret([]) + ), + c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), + c.setLocal( + "nChunks", + c.i32_add( + c.i32_div_u( + c.i32_sub( + c.i32_shl( + c.getLocal("scalarSize"), + c.i32_const(3) + ), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ), + + + // Allocate memory + + c.setLocal( + "itBit", + c.i32_mul( + c.i32_sub( + c.getLocal("nChunks"), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_lt_s( + c.getLocal("itBit"), + c.i32_const(0) + ) + ), + + // Double nChunk times + c.if( + c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), + [ + ...c.setLocal("j", c.i32_const(0)), + ...c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("chunkSize") + ) + ), + + c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )) + ] + ), + + c.call( + fnName + "_chunk", + c.getLocal("pBases"), + c.getLocal("pScalars"), + c.getLocal("scalarSize"), + c.getLocal("n"), + c.getLocal("itBit"), + c.getLocal("chunkSize"), + aux + ), + + c.call( + prefix + "_add", + c.getLocal("pr"), + aux, + c.getLocal("pr") + ), + c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), + c.br(0) + )) + ); + } + + function buildReduceTable() { + const f = module.addFunction(fnName + "_reduceTable"); + f.addParam("pTable", "i32"); + f.addParam("p", "i32"); // Number of bits of the table + f.addLocal("half", "i32"); + f.addLocal("it1", "i32"); + f.addLocal("it2", "i32"); + f.addLocal("pAcc", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eq(c.getLocal("p"), c.i32_const(1)), + c.ret([]) + ), + c.setLocal( + "half", + c.i32_shl( + c.i32_const(1), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ), + + c.setLocal("it1", c.getLocal("pTable")), + c.setLocal( + "it2", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("half"), + c.i32_const(n8g) + ) + ) + ), + c.setLocal("pAcc", + c.i32_sub( + c.getLocal("it2"), + c.i32_const(n8g) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it1"), + c.getLocal("pAcc") + ) + ), + c.call( + prefix + "_add", + c.getLocal("it1"), + c.getLocal("it2"), + c.getLocal("it1") + ), + c.call( + prefix + "_add", + c.getLocal("pAcc"), + c.getLocal("it2"), + c.getLocal("pAcc") + ), + c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), + c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), + c.br(0) + )), + + c.call( + fnName + "_reduceTable", + c.getLocal("pTable"), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("p"))), + c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) + ); + } + + buildGetChunk(); + buildReduceTable(); + buildMutiexpChunk(); + buildMultiexp(); + + module.exportFunction(fnName); + module.exportFunction(fnName +"_chunk"); + + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildTimesScalarNAF = build_timesscalarnaf; +//const buildTimesScalar = require("./build_timesscalar"); +const buildBatchConvertion = build_batchconvertion; +const buildMultiexp$1 = build_multiexp; + +var build_curve_jacobian_a0 = function buildCurve(module, prefix, prefixField, pB) { + + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64*3 + }; + + function buildIsZero() { + const f = module.addFunction(prefix + "_isZero"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8*2) + ) + )); + } + function buildIsZeroAffine() { + const f = module.addFunction(prefix + "_isZeroAffine"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_and( + c.call( + prefixField + "_isZero", + c.getLocal("p1") + ), + c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8) + ) + ) + ) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix + "_copy"); + f.addParam("ps", "i32"); + f.addParam("pd", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i. +*/ + +const bigInt$3 = BigIntegerExports; +const utils$7 = utils$b; + +var build_fft = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { + + const n64f = module.modules[fPrefix].n64; + const n8f = n64f*8; + + const n64g = module.modules[gPrefix].n64; + const n8g = n64g*8; + + const q = module.modules[fPrefix].q; + + let rem = q.minus(bigInt$3(1)); + let maxBits = 0; + while (!rem.isOdd()) { + maxBits ++; + rem = rem.shiftRight(1); + } + + let nr = bigInt$3(2); + + while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); + + // console.log(nr); + + const w = new Array(maxBits+1); + w[maxBits] = nr.modPow(rem, q); + + let n=maxBits-1; + while (n>=0) { + w[n] = w[n+1].modPow(2, q); + n--; + } + + const bytes = []; + const R = bigInt$3(1).shiftLeft(n8f*8).mod(q); + + for (let i=0; i> i); + } + } + return r; + } + + const rtable = Array(256); + for (let i=0; i<256; i++) { + rtable[i] = rev(i); + } + + const REVTABLE = module.alloc(rtable); + + + function buildLog2() { + const f = module.addFunction(prefix+"__log2"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + f.addLocal("bits", "i32"); + f.addLocal("aux", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ) + ); + f.addCode(c.setLocal("bits", c.i32_const(0))); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_eqz(c.getLocal("aux")) + ), + + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("aux"), + c.i32_const(1) + ) + ), + + c.setLocal( + "bits", + c.i32_add( + c.getLocal("bits"), + c.i32_const(1) + ) + ), + + c.br(0) + ))); + + f.addCode(c.if( + c.i32_ne( + c.getLocal("n"), + c.i32_shl( + c.i32_const(1), + c.getLocal("bits") + ) + ), + c.unreachable() + )); + + f.addCode(c.if( + c.i32_gt_u( + c.getLocal("bits"), + c.i32_const(maxBits) + ), + c.unreachable() + )); + + f.addCode(c.getLocal("bits")); + } + + function buildFFT() { + const f = module.addFunction(prefix+"_fft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + + f.addLocal("bits", "i32"); + + const c = f.getCodeBuilder(); + + const One = c.i32_const(module.alloc(n8f)); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.call(fPrefix + "_one", One), + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(0), + One + ) + ); + + } + + function buildIFFT() { + const f = module.addFunction(prefix+"_ifft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("bits", "i32"); + f.addLocal("pInv2", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.setLocal( + "pInv2", + c.i32_add( + c.i32_const(INV2), + c.i32_mul( + c.getLocal("bits"), + c.i32_const(n8f) + ) + ) + ), + + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(1), + c.getLocal("pInv2") + ), + ); + } + + function buildRawFFT() { + const f = module.addFunction(prefix+"_rawfft"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); // 2 power + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + + f.addLocal("s", "i32"); + f.addLocal("k", "i32"); + f.addLocal("j", "i32"); + f.addLocal("m", "i32"); + f.addLocal("mdiv2", "i32"); + f.addLocal("n", "i32"); + f.addLocal("pwm", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call(prefix + "__reversePermutation", c.getLocal("px"), c.getLocal("bits")), + c.setLocal("n", c.i32_shl(c.i32_const(1), c.getLocal("bits"))), + c.setLocal("s", c.i32_const(1)), + c.block(c.loop( + c.br_if( + 1, + c.i32_gt_u( + c.getLocal("s"), + c.getLocal("bits") + ) + ), + c.setLocal("m", c.i32_shl(c.i32_const(1), c.getLocal("s"))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("s"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("k", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("k"), + c.getLocal("n") + ) + ), + + c.call(fPrefix + "_one", W), + + c.setLocal("mdiv2", c.i32_shr_u(c.getLocal("m"), c.i32_const(1)) ), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("j"), + c.getLocal("mdiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_add( + c.getLocal("k"), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.i32_mul( + c.getLocal("mdiv2"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("k", c.i32_add(c.getLocal("k"), c.getLocal("m"))), + c.br(0) + )), + + c.setLocal("s", c.i32_add(c.getLocal("s"), c.i32_const(1))), + c.br(0) + )), + c.call( + prefix + "__fftFinal", + c.getLocal("px"), + c.getLocal("bits"), + c.getLocal("reverse"), + c.getLocal("mulFactor") + ) + ); + } + + + function buildFinalInverse() { + const f = module.addFunction(prefix+"__fftFinal"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + f.addLocal("n", "i32"); + f.addLocal("ndiv2", "i32"); + f.addLocal("pInv2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("mask", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.if( + c.i32_and( + c.i32_eqz(c.getLocal("reverse")), + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")) + ), + c.ret([]) + ), + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + + c.setLocal("mask", c.i32_sub( c.getLocal("n") , c.i32_const(1))), + c.setLocal("i", c.i32_const(1)), + c.setLocal( + "ndiv2", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.getLocal("reverse"), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1") ), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")), + ], + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , T , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF , c.getLocal("idx1") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )), + + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF, c.getLocal("px") , c.getLocal("mulFactor"), c.getLocal("px")), + ...c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ) + ), + ...c.call(opGtimesF, c.getLocal("idx2"),c.getLocal("mulFactor"), c.getLocal("idx2")) + ] + ) + ); + } + + function buildReversePermutation() { + const f = module.addFunction(prefix+"__reversePermutation"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addLocal("n", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ri", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("ri", c.call(prefix + "__rev", c.getLocal("i"), c.getLocal("bits"))), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ri"), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.i32_lt_u( + c.getLocal("i"), + c.getLocal("ri") + ), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1")), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")) + ] + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )) + ); + } + + function buildRev() { + const f = module.addFunction(prefix+"__rev"); + f.addParam("x", "i32"); + f.addParam("bits", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_rotl( + c.i32_add( + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.getLocal("x"), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(24) + ), + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(8) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(16) + ), + ), + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(16) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(8) + ), + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(24) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + ) + ), + c.getLocal("bits") + ) + ); + } + + + function buildFFTJoin() { + const f = module.addFunction(prefix+"_fftJoin"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W, + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildFFTJoinExt() { + const f = module.addFunction(prefix+"_fftJoinExt"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + U + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pShiftToM"), + c.getLocal("idx2") + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + U, + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTJoinExtInv() { + const f = module.addFunction(prefix+"_fftJoinExtInv"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + U, + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pSConst"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + c.getLocal("idx1") + ), + + c.call( + gPrefix + "_sub", + U, + c.getLocal("idx1"), + c.getLocal("idx1") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pSConst"), + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildPrepareLagrangeEvaluation() { + const f = module.addFunction(prefix+"_prepareLagrangeEvaluation"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx2"), + U, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + U, + c.getLocal("pSConst"), + c.getLocal("idx1"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTMix() { + const f = module.addFunction(prefix+"_fftMix"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("exp", "i32"); + f.addLocal("nGroups", "i32"); + f.addLocal("nPerGroup", "i32"); + f.addLocal("nPerGroupDiv2", "i32"); + f.addLocal("pairOffset", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pwm", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("nPerGroup", c.i32_shl(c.i32_const(1), c.getLocal("exp"))), + c.setLocal("nPerGroupDiv2", c.i32_shr_u(c.getLocal("nPerGroup"), c.i32_const(1))), + c.setLocal("nGroups", c.i32_shr_u(c.getLocal("n"), c.getLocal("exp"))), + c.setLocal("pairOffset", c.i32_mul(c.getLocal("nPerGroupDiv2"), c.i32_const(n8g))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("exp"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nGroups") + ) + ), + c.call( fPrefix + "_one", W), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nPerGroupDiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_add( + c.i32_mul( + c.getLocal("i"), + c.getLocal("nPerGroup") + ), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.getLocal("pairOffset") + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + // Reverse all and multiply by factor + function buildFFTFinal() { + const f = module.addFunction(prefix+"_fftFinal"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("factor", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ndiv2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("ndiv2", c.i32_shr_u(c.getLocal("n"), c.i32_const(1))), + c.if( + c.i32_and( + c.getLocal("n"), + c.i32_const(1) + ), + c.call( + opGtimesF, + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + c.getLocal("factor"), + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + ), + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_sub( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("factor"), + T + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("factor"), + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + T, + c.getLocal("idx1"), + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + buildRev(); + buildReversePermutation(); + buildFinalInverse(); + buildRawFFT(); + buildLog2(); + buildFFT(); + buildIFFT(); + buildFFTJoin(); + buildFFTJoinExt(); + buildFFTJoinExtInv(); + buildFFTMix(); + buildFFTFinal(); + buildPrepareLagrangeEvaluation(); + + module.exportFunction(prefix+"_fft"); + module.exportFunction(prefix+"_ifft"); + module.exportFunction(prefix+"_rawfft"); + module.exportFunction(prefix+"_fftJoin"); + module.exportFunction(prefix+"_fftJoinExt"); + module.exportFunction(prefix+"_fftJoinExtInv"); + module.exportFunction(prefix+"_fftMix"); + module.exportFunction(prefix+"_fftFinal"); + module.exportFunction(prefix+"_prepareLagrangeEvaluation"); + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_pol = function buildPol(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("lastp", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("p", c.getLocal("px")), + c.setLocal( + "lastp", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("p"), + c.getLocal("lastp") + ) + ), + c.call(prefixField + "_zero", c.getLocal("p")), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildConstructLC() { + const f = module.addFunction(prefix+"_constructLC"); + f.addParam("ppolynomials", "i32"); + f.addParam("psignals", "i32"); + f.addParam("nSignals", "i32"); + f.addParam("pres", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pp", "i32"); + f.addLocal("ps", "i32"); + f.addLocal("pd", "i32"); + f.addLocal("ncoefs", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.setLocal("pp", c.getLocal("ppolynomials")), + c.setLocal("ps", c.getLocal("psignals")), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nSignals") + ) + ), + + c.setLocal("ncoefs", c.i32_load(c.getLocal("pp"))), + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("ncoefs") + ) + ), + + c.setLocal( + "pd", + c.i32_add( + c.getLocal("pres"), + c.i32_mul( + c.i32_load(c.getLocal("pp")), + c.i32_const(n8) + ) + ) + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + + c.call( + prefixField + "_mul", + c.getLocal("ps"), + c.getLocal("pp"), + aux + ), + + c.call( + prefixField + "_add", + aux, + c.getLocal("pd"), + c.getLocal("pd") + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(n8))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + } + + buildZero(); + buildConstructLC(); + + + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_constructLC"); + + return prefix; + + + + +}; + +var build_qap = function buildQAP(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildBuildABC() { + const f = module.addFunction(prefix+"_buildABC"); + f.addParam("pCoefs", "i32"); + f.addParam("nCoefs", "i32"); + f.addParam("pWitness", "i32"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("offsetOut", "i32"); + f.addParam("nOut", "i32"); + f.addParam("offsetWitness", "i32"); + f.addParam("nWitness", "i32"); + f.addLocal("it", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("last", "i32"); + f.addLocal("m", "i32"); + f.addLocal("c", "i32"); + f.addLocal("s", "i32"); + f.addLocal("pOut", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + + // Set output a and b to 0 + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call(prefixField + "_zero", c.getLocal("ita")), + c.call(prefixField + "_zero", c.getLocal("itb")), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.br(0) + )), + + + c.setLocal("it", c.getLocal("pCoefs")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pCoefs"), + c.i32_mul( + c.getLocal("nCoefs"), + c.i32_const(n8+12) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it"), + c.getLocal("last") + ) + ), + c.setLocal( + "s", + c.i32_load(c.getLocal("it"), 8) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("s"), + c.getLocal("offsetWitness"), + ), + c.i32_ge_u( + c.getLocal("s"), + c.i32_add( + c.getLocal("offsetWitness"), + c.getLocal("nWitness"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + + c.setLocal( + "m", + c.i32_load(c.getLocal("it")) + ), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(0)), + c.setLocal("pOut", c.getLocal("pA")), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(1)), + c.setLocal("pOut", c.getLocal("pB")), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ) + ), + c.setLocal( + "c", + c.i32_load(c.getLocal("it"), 4) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("c"), + c.getLocal("offsetOut"), + ), + c.i32_ge_u( + c.getLocal("c"), + c.i32_add( + c.getLocal("offsetOut"), + c.getLocal("nOut"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + c.setLocal( + "pOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("c"), + c.getLocal("offsetOut") + ), + c.i32_const(n8) + ) + ) + ), + c.call( + prefixField + "_mul", + c.i32_add( + c.getLocal("pWitness"), + c.i32_mul( + c.i32_sub(c.getLocal("s"), c.getLocal("offsetWitness")), + c.i32_const(n8) + ) + ), + c.i32_add( c.getLocal("it"), c.i32_const(12)), + aux + ), + c.call( + prefixField + "_add", + c.getLocal("pOut"), + aux, + c.getLocal("pOut"), + ), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + c.br(0) + )), + + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("it", c.getLocal("pC")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("it") + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8))), + c.br(0) + )), + + ); + } + + function buildJoinABC() { + const f = module.addFunction(prefix+"_joinABC"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("n", "i32"); + f.addParam("pP", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itc", "i32"); + f.addLocal("itp", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("itc", c.getLocal("pC")), + c.setLocal("itp", c.getLocal("pP")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + aux + ), + c.call( + prefixField + "_sub", + aux, + c.getLocal("itc"), + c.getLocal("itp"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itc", c.i32_add(c.getLocal("itc"), c.i32_const(n8))), + c.setLocal("itp", c.i32_add(c.getLocal("itp"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildBatchAdd() { + const f = module.addFunction(prefix+"_batchAdd"); + f.addParam("pa", "i32"); + f.addParam("pb", "i32"); + f.addParam("n", "i32"); + f.addParam("pr", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itr", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("ita", c.getLocal("pa")), + c.setLocal("itb", c.getLocal("pb")), + c.setLocal("itr", c.getLocal("pr")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pa"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_add", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("itr"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itr", c.i32_add(c.getLocal("itr"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + buildBuildABC(); + buildJoinABC(); + buildBatchAdd(); + + module.exportFunction(prefix + "_buildABC"); + module.exportFunction(prefix + "_joinABC"); + module.exportFunction(prefix + "_batchAdd"); + + return prefix; + +}; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +var build_applykey = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { + + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pFirst", "i32"); + f.addParam("pInc", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("pOldFree", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pFrom", "i32"); + f.addLocal("pTo", "i32"); + + const c = f.getCodeBuilder(); + + const t = c.i32_const(module.alloc(sizeF)); + + f.addCode( + c.setLocal("pFrom", c.getLocal("pIn")), + c.setLocal("pTo", c.getLocal("pOut")), + ); + + // t = first + f.addCode( + c.call( + frPrefix + "_copy", + c.getLocal("pFirst"), + t + ) + ); + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call( + opGtimesF, + c.getLocal("pFrom"), + t, + c.getLocal("pTo") + ), + c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), + c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + + // t = t* inc + c.call( + frPrefix + "_mul", + t, + c.getLocal("pInc"), + t + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + module.exportFunction(fnName); + +}; + +const bigInt$2 = BigIntegerExports; +const utils$6 = utils$b; + +const buildF1m$1 =build_f1m; +const buildF1$1 =build_f1; +const buildF2m$1 =build_f2m; +const buildF3m$1 =build_f3m; +const buildCurve$1 =build_curve_jacobian_a0; +const buildFFT$2 = build_fft; +const buildPol$1 = build_pol; +const buildQAP$1 = build_qap; +const buildApplyKey$1 = build_applykey; + +var build_bn128 = function buildBN128(module, _prefix) { + + const prefix = _prefix || "bn128"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = bigInt$2("21888242871839275222246405745257275088696311157297823662689037894645226208583"); + const r = bigInt$2("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + + + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + const frsize = n8; + const f1size = n8; + const f2size = f1size * 2; + const ftsize = f1size * 12; + + const pr = module.alloc(utils$6.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m$1(module, q, "f1m"); + buildF1$1(module, r, "fr", "frm"); + + const pG1b = module.alloc(utils$6.bigInt2BytesLE( toMontgomery(bigInt$2(3)), f1size )); + const g1mPrefix = buildCurve$1(module, "g1m", "f1m", pG1b); + + buildFFT$2(module, "frm", "frm", "frm", "frm_mul"); + + buildPol$1(module, "pol", "frm"); + buildQAP$1(module, "qap", "frm"); + + const f2mPrefix = buildF2m$1(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery(bigInt$2("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(bigInt$2("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) + ]); + const g2mPrefix = buildCurve$1(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT$2(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT$2(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey$1(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); + buildApplyKey$1(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); + buildApplyKey$1(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); + buildApplyKey$1(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); + buildApplyKey$1(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); + + function toMontgomery(a) { + return bigInt$2(a).times( bigInt$2.one.shiftLeft(f1size*8)).mod(q); + } + + const G1gen = [ + bigInt$2("1"), + bigInt$2("2"), + bigInt$2.one + ]; + + const pG1gen = module.alloc( + [ + ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + bigInt$2.zero, + bigInt$2.one, + bigInt$2.zero + ]; + + const pG1zero = module.alloc( + [ + ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + bigInt$2("10857046999023057135944570762232829481370756359578518086990519993285655852781"), + bigInt$2("11559732032986387107991004021392285783925812861821192530917403151452391805634"), + ],[ + bigInt$2("8495653923123431417604973247489272438418190587263600148770280649306958101930"), + bigInt$2("4082367875863433681332203403145435568316851327593401208105741076214120093531"), + ],[ + bigInt$2.one, + bigInt$2.zero, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + bigInt$2.zero, + bigInt$2.zero, + ],[ + bigInt$2.one, + bigInt$2.zero, + ],[ + bigInt$2.zero, + bigInt$2.zero, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pNonResidueF6 = module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery(9), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery( bigInt$2(2).modInv(q)), f1size ), + ...utils$6.bigInt2BytesLE( bigInt$2(0), f1size ) + ]); + + const pAltBn128Twist = pNonResidueF6; + + const pTwistCoefB = module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), + ]); + + function build_mulNR6() { + const f = module.addFunction(prefix + "_mulNR6"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.getLocal("x"), + c.getLocal("pr") + ) + ); + } + build_mulNR6(); + + const f6mPrefix = buildF3m$1(module, prefix+"_mulNR6", "f6m", "f2m"); + + function build_mulNR12() { + const f = module.addFunction(prefix + "_mulNR12"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), + ) + ); + } + build_mulNR12(); + + const ftmPrefix = buildF2m$1(module, prefix+"_mulNR12", "ftm", f6mPrefix); + + + const ateLoopCount = bigInt$2("29793968203157093288"); + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8; + const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; + + + module.modules[prefix] = { + n64: n64, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + prePSize: prePSize, + preQSize: preQSize, + r: r.toString(), + q: q.toString() + }; + + // console.log("PrePSize: " +prePSize); + // console.log("PreQSize: " +preQSize); + + const finalExpZ = bigInt$2("4965661367192848881"); + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt$2.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt$2.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("pQ", "i32"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X2 = c.getLocal("pQ"); + const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const D = ELL_VW; + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + // D = X1 - X2*Z1 + c.call(f2mPrefix + "_mul", X2, Z1, D), + c.call(f2mPrefix + "_sub", X1, D, D), + + // E = Y1 - Y2*Z1 + c.call(f2mPrefix + "_mul", Y2, Z1, E), + c.call(f2mPrefix + "_sub", Y1, E, E), + + // F = D^2 + c.call(f2mPrefix + "_square", D, F), + + // G = E^2 + c.call(f2mPrefix + "_square", E, G), + + // H = D*F + c.call(f2mPrefix + "_mul", D, F, H), + + // I = X1 * F + c.call(f2mPrefix + "_mul", X1, F, I), + + // J = H + Z1*G - (I+I) + c.call(f2mPrefix + "_add", I, I, AUX), + c.call(f2mPrefix + "_mul", Z1, G, J), + c.call(f2mPrefix + "_add", H, J, J), + c.call(f2mPrefix + "_sub", J, AUX, J), + + + // X3 (X1) = D*J + c.call(f2mPrefix + "_mul", D, J, X1), + + // Y3 (Y1) = E*(I-J)-(H*Y1) + c.call(f2mPrefix + "_mul", H, Y1, Y1), + c.call(f2mPrefix + "_sub", I, J, AUX), + c.call(f2mPrefix + "_mul", E, AUX, AUX), + c.call(f2mPrefix + "_sub", AUX, Y1, Y1), + + // Z3 (Z1) = Z1*H + c.call(f2mPrefix + "_mul", Z1, H, Z1), + + // ell_0 = xi * (E * X2 - D * Y2) + c.call(f2mPrefix + "_mul", D, Y2, AUX), + c.call(f2mPrefix + "_mul", E, X2, ELL_0), + c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), + c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), + + + // ell_VV = - E (later: * xP) + c.call(f2mPrefix + "_neg", E, ELL_VV), + + // ell_VW = D (later: * yP ) + // Already assigned + + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const A = c.i32_const(module.alloc(f2size)); + const B = c.i32_const(module.alloc(f2size)); + const C = c.i32_const(module.alloc(f2size)); + const D = c.i32_const(module.alloc(f2size)); + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const E2 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // A = X1 * Y1 / 2 + c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), + c.call(f2mPrefix + "_mul", X1, A, A), + + // B = Y1^2 + c.call(f2mPrefix + "_square", Y1, B), + + // C = Z1^2 + c.call(f2mPrefix + "_square", Z1, C), + + // D = 3 * C + c.call(f2mPrefix + "_add", C, C, D), + c.call(f2mPrefix + "_add", D, C, D), + + // E = twist_b * D + c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), + + // F = 3 * E + c.call(f2mPrefix + "_add", E, E, F), + c.call(f2mPrefix + "_add", E, F, F), + + // G = (B+F)/2 + c.call(f2mPrefix + "_add", B, F, G), + c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), + + // H = (Y1+Z1)^2-(B+C) + c.call(f2mPrefix + "_add", B, C, AUX), + c.call(f2mPrefix + "_add", Y1, Z1, H), + c.call(f2mPrefix + "_square", H, H), + c.call(f2mPrefix + "_sub", H, AUX, H), + + // I = E-B + c.call(f2mPrefix + "_sub", E, B, I), + + // J = X1^2 + c.call(f2mPrefix + "_square", X1, J), + + // E_squared = E^2 + c.call(f2mPrefix + "_square", E, E2), + + // X3 (X1) = A * (B-F) + c.call(f2mPrefix + "_sub", B, F, AUX), + c.call(f2mPrefix + "_mul", A, AUX, X1), + + // Y3 (Y1) = G^2 - 3*E^2 + c.call(f2mPrefix + "_add", E2, E2, AUX), + c.call(f2mPrefix + "_add", E2, AUX, AUX), + c.call(f2mPrefix + "_square", G, Y1), + c.call(f2mPrefix + "_sub", Y1, AUX, Y1), + + // Z3 (Z1) = B * H + c.call(f2mPrefix + "_mul", B, H, Z1), + + // ell_0 = xi * I + c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), + + // ell_VW = - H (later: * yP) + c.call(f2mPrefix + "_neg", H, ELL_VW), + + // ell_VV = 3*J (later: * xP) + c.call(f2mPrefix + "_add", J, J, ELL_VV), + c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), + + ); + } + + function buildMulByQ() { + const f = module.addFunction(prefix + "_mulByQ"); + f.addParam("p1", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("p1"); + const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); + const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); + const x3 = c.getLocal("pr"); + const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); + const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); + + const MulByQX = c.i32_const(module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), + ])); + + const MulByQY = c.i32_const(module.alloc([ + ...utils$6.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), + ...utils$6.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), + ])); + + f.addCode( + // The frobeniusMap(1) in this field, is the conjugate + c.call(f2mPrefix + "_conjugate", x, x3), + c.call(f2mPrefix + "_mul", MulByQX, x3, x3), + c.call(f2mPrefix + "_conjugate", y, y3), + c.call(f2mPrefix + "_mul", MulByQY, y3, y3), + c.call(f2mPrefix + "_conjugate", z, z3), + ); + } + + + function buildPrepareG2() { + buildMulByQ(); + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const QX = c.getLocal("pQ"); + c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); + c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + const RX = c.i32_const(pR); + const RY = c.i32_const(pR+f2size); + const RZ = c.i32_const(pR+2*f2size); + + const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); + const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); + c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); + + const pQ1 = module.alloc(f2size*3); + const Q1 = c.i32_const(pQ1); + + const pQ2 = module.alloc(f2size*3); + const Q2 = c.i32_const(pQ2); + c.i32_const(pQ2); + const Q2Y = c.i32_const(pQ2 + f2size); + c.i32_const(pQ2 + f2size*2); + + f.addCode( + c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine + c.call(f2mPrefix + "_copy", cQX, RX), + c.call(f2mPrefix + "_copy", cQY, RY), + c.call(f2mPrefix + "_one", RZ), + ); + + f.addCode( + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + f.addCode( + c.call(prefix + "_mulByQ", cQX, Q1), + c.call(prefix + "_mulByQ", Q1, Q2) + ); + + f.addCode( + c.call(f2mPrefix + "_neg", Q2Y, Q2Y), + + c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ); + } + + function buildMulBy024Old() { + const f = module.addFunction(prefix+ "__mulBy024Old"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + + const pAUX12 = module.alloc(ftsize); + const AUX12 = c.i32_const(pAUX12); + const AUX12_0 = c.i32_const(pAUX12); + const AUX12_2 = c.i32_const(pAUX12+f2size); + const AUX12_4 = c.i32_const(pAUX12+f2size*2); + const AUX12_6 = c.i32_const(pAUX12+f2size*3); + const AUX12_8 = c.i32_const(pAUX12+f2size*4); + const AUX12_10 = c.i32_const(pAUX12+f2size*5); + + f.addCode( + + c.call(f2mPrefix + "_copy", x0, AUX12_0), + c.call(f2mPrefix + "_zero", AUX12_2), + c.call(f2mPrefix + "_copy", x2, AUX12_4), + c.call(f2mPrefix + "_zero", AUX12_6), + c.call(f2mPrefix + "_copy", x4, AUX12_8), + c.call(f2mPrefix + "_zero", AUX12_10), + c.call(ftmPrefix + "_mul", AUX12, z0, z0), + ); + } + + function buildMulBy024() { + const f = module.addFunction(prefix+ "__mulBy024"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); + const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); + const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); + const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); + const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const s0 = c.i32_const(module.alloc(f2size)); + const T3 = c.i32_const(module.alloc(f2size)); + const T4 = c.i32_const(module.alloc(f2size)); + const D0 = c.i32_const(module.alloc(f2size)); + const D2 = c.i32_const(module.alloc(f2size)); + const D4 = c.i32_const(module.alloc(f2size)); + const S1 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // D0 = z0 * x0; + c.call(f2mPrefix + "_mul", z0, x0, D0), + // D2 = z2 * x2; + c.call(f2mPrefix + "_mul", z2, x2, D2), + // D4 = z4 * x4; + c.call(f2mPrefix + "_mul", z4, x4, D4), + // t2 = z0 + z4; + c.call(f2mPrefix + "_add", z0, z4, t2), + // t1 = z0 + z2; + c.call(f2mPrefix + "_add", z0, z2, t1), + // s0 = z1 + z3 + z5; + c.call(f2mPrefix + "_add", z1, z3, s0), + c.call(f2mPrefix + "_add", s0, z5, s0), + + + // For z.a_.a_ = z0. + // S1 = z1 * x2; + c.call(f2mPrefix + "_mul", z1, x2, S1), + // T3 = S1 + D4; + c.call(f2mPrefix + "_add", S1, D4, T3), + // T4 = my_Fp6::non_residue * T3 + D0; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + c.call(f2mPrefix + "_add", T4, D0, z0), + // z0 = T4; + + // For z.a_.b_ = z1 + // T3 = z5 * x4; + c.call(f2mPrefix + "_mul", z5, x4, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T3 = T3 + D2; + c.call(f2mPrefix + "_add", T3, D2, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z1 * x0; + c.call(f2mPrefix + "_mul", z1, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z1), + // z1 = T4; + + + + // For z.a_.c_ = z2 + // t0 = x0 + x2; + c.call(f2mPrefix + "_add", x0, x2, t0), + // T3 = t1 * t0 - D0 - D2; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D0, D2, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = z3 * x4; + c.call(f2mPrefix + "_mul", z3, x4, T4), + // S1 = S1 + T4; + c.call(f2mPrefix + "_add", S1, T4, S1), + + + // For z.b_.a_ = z3 (z3 needs z2) + // t0 = z2 + z4; + c.call(f2mPrefix + "_add", z2, z4, t0), + // T3 = T3 + T4; + // z2 = T3; + c.call(f2mPrefix + "_add", T3, T4, z2), + // t1 = x2 + x4; + c.call(f2mPrefix + "_add", x2, x4, t1), + // T3 = t0 * t1 - D2 - D4; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D2, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z3 * x0; + c.call(f2mPrefix + "_mul", z3, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z3), + // z3 = T4; + + // For z.b_.b_ = z4 + // T3 = z5 * x2; + c.call(f2mPrefix + "_mul", z5, x2, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // t0 = x0 + x4; + c.call(f2mPrefix + "_add", x0, x4, t0), + // T3 = t2 * t0 - D0 - D4; + c.call(f2mPrefix + "_mul", t2, t0, T3), + c.call(f2mPrefix + "_add", D0, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z4), + // z4 = T4; + + // For z.b_.c_ = z5. + // t0 = x0 + x2 + x4; + c.call(f2mPrefix + "_add", x0, x2, t0), + c.call(f2mPrefix + "_add", t0, x4, t0), + // T3 = s0 * t0 - S1; + c.call(f2mPrefix + "_mul", s0, t0, T3), + c.call(f2mPrefix + "_sub", T3, S1, z5), + // z5 = T3; + + ); + } + + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP_PX = c.getLocal("ppreP"); + const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + + const pVW = module.alloc(f2size); + const VW = c.i32_const(pVW); + const pVV = module.alloc(f2size); + const VV = c.i32_const(pVV); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(ftmPrefix + "_square", F, F), + + c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + + ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + + ); + + f.addCode( + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ); + + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + ], + [ + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt$2("16469823323077808223889137241176536799009286646108169935659301613961712198316")], + [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt$2("0")], + [bigInt$2("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt$2("303847389135065887422783454877609941456349188919719272345083954437860409601")], + [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], + [bigInt$2("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt$2("5722266937896532885780051958958348231143373700109372999374820235121374419868")], + [bigInt$2("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt$2("0")], + [bigInt$2("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt$2("5418419548761466998357268504080738289687024511189653727029736280683514010267")], + [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], + [bigInt$2("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt$2("21584395482704209334823622290379665147239961968378104390343953940207365798982")], + [bigInt$2("2203960485148121921418603742825762020974279258880205651967"), bigInt$2("0")], + [bigInt$2("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt$2("16165975933942742336466353786298926857552937457188450663314217659523851788715")], + ] + ]; + + const F6 = [ + [ + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("1"), bigInt$2("0")], + ], + [ + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt$2("10307601595873709700152284273816112264069230130616436755625194854815875713954")], + [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], + [bigInt$2("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt$2("2236595495967245188281701248203181795121068902605861227855261137820944008926")], + [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], + [bigInt$2("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt$2("9344045779998320333812420223237981029506012124075525679208581902008406485703")], + ], + [ + [bigInt$2("1"), bigInt$2("0")], + [bigInt$2("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt$2("19937756971775647987995932169929341994314640652964949448313374472400716661030")], + [bigInt$2("2203960485148121921418603742825762020974279258880205651966"), bigInt$2("0")], + [bigInt$2("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt$2("16208900380737693084919495127334387981393726419856888799917914180988844123039")], + [bigInt$2("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt$2("0")], + [bigInt$2("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt$2("7629828391165209371577384193250820201684255241773809077146787135900891633097")], + ] + ]; + + const f = module.addFunction(prefix+ "__frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$6.bigInt2BytesLE(toMontgomery(coef[0]), 32), + ...utils$6.bigInt2BytesLE(toMontgomery(coef[1]), 32), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt$2(a[0]); + const ac1 = bigInt$2(a[1]); + const bc0 = bigInt$2(b[0]); + const bc1 = bigInt$2(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + + function buildFinalExponentiationFirstChunk() { + + const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const eltC0 = elt; + const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); + const r = c.getLocal("r"); + const pA = module.alloc(ftsize); + const A = c.i32_const(pA); + const Ac0 = A; + const Ac1 = c.i32_const(pA + n8*6); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + + f.addCode( + // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); + c.call(f6mPrefix + "_copy", eltC0, Ac0), + c.call(f6mPrefix + "_neg", eltC1, Ac1), + + // const alt_bn128_Fq12 B = elt.inverse(); + c.call(ftmPrefix + "_inverse", elt, B), + + // const alt_bn128_Fq12 C = A * B; + c.call(ftmPrefix + "_mul", A, B, C), + // const alt_bn128_Fq12 D = C.Frobenius_map(2); + c.call(prefix + "__frobeniusMap2", C, D), + // const alt_bn128_Fq12 result = D * C; + c.call(ftmPrefix + "_mul", C, D, r), + ); + } + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + module.alloc(utils$6.bigInt2BytesLE(exponent, 32)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildFinalExponentiationLastChunk() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, "w0"); + + const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const A = c.i32_const(module.alloc(ftsize)); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + const E = c.i32_const(module.alloc(ftsize)); + const F = c.i32_const(module.alloc(ftsize)); + const G = c.i32_const(module.alloc(ftsize)); + const H = c.i32_const(module.alloc(ftsize)); + const I = c.i32_const(module.alloc(ftsize)); + const J = c.i32_const(module.alloc(ftsize)); + const K = c.i32_const(module.alloc(ftsize)); + const L = c.i32_const(module.alloc(ftsize)); + const M = c.i32_const(module.alloc(ftsize)); + const N = c.i32_const(module.alloc(ftsize)); + const O = c.i32_const(module.alloc(ftsize)); + const P = c.i32_const(module.alloc(ftsize)); + const Q = c.i32_const(module.alloc(ftsize)); + const R = c.i32_const(module.alloc(ftsize)); + const S = c.i32_const(module.alloc(ftsize)); + const T = c.i32_const(module.alloc(ftsize)); + const U = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + + // A = exp_by_neg_z(elt) // = elt^(-z) + c.call(prefix + "__cyclotomicExp_w0", elt, A), + c.call(ftmPrefix + "_conjugate", A, A), + // B = A^2 // = elt^(-2*z) + c.call(prefix + "__cyclotomicSquare", A, B), + // C = B^2 // = elt^(-4*z) + c.call(prefix + "__cyclotomicSquare", B, C), + // D = C * B // = elt^(-6*z) + c.call(ftmPrefix + "_mul", C, B, D), + // E = exp_by_neg_z(D) // = elt^(6*z^2) + c.call(prefix + "__cyclotomicExp_w0", D, E), + c.call(ftmPrefix + "_conjugate", E, E), + // F = E^2 // = elt^(12*z^2) + c.call(prefix + "__cyclotomicSquare", E, F), + // G = epx_by_neg_z(F) // = elt^(-12*z^3) + c.call(prefix + "__cyclotomicExp_w0", F, G), + c.call(ftmPrefix + "_conjugate", G, G), + // H = conj(D) // = elt^(6*z) + c.call(ftmPrefix + "_conjugate", D, H), + // I = conj(G) // = elt^(12*z^3) + c.call(ftmPrefix + "_conjugate", G, I), + // J = I * E // = elt^(12*z^3 + 6*z^2) + c.call(ftmPrefix + "_mul", I, E, J), + // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) + c.call(ftmPrefix + "_mul", J, H, K), + // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) + c.call(ftmPrefix + "_mul", K, B, L), + // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) + c.call(ftmPrefix + "_mul", K, E, M), + + // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) + c.call(ftmPrefix + "_mul", M, elt, N), + + // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) + c.call(prefix + "__frobeniusMap1", L, O), + // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", O, N, P), + // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) + c.call(prefix + "__frobeniusMap2", K, Q), + // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", Q, P, R), + // S = conj(elt) // = elt^(-1) + c.call(ftmPrefix + "_conjugate", elt, S), + // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) + c.call(ftmPrefix + "_mul", S, L, T), + // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) + c.call(prefix + "__frobeniusMap3", T, U), + // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", U, R, result), + // result = V + ); + } + + + function buildFinalExponentiation() { + buildFinalExponentiationFirstChunk(); + buildFinalExponentiationLastChunk(); + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); + + f.addCode( + c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), + c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt$2("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); + + const pExponent = module.alloc(utils$6.bigInt2BytesLE( exponent, 352 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), + ); + } + + + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8q; + const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = true; + + const finalExpZ = bigInt$1("15132376222941642752"); + + + module.modules[prefix] = { + n64q: n64q, + n64r: n64r, + n8q: n8q, + n8r: n8r, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + r: r, + q: q, + prePSize: prePSize, + preQSize: preQSize + }; + + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt$1.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt$1.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("R", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const t0 = c.getLocal("r"); + const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + + const zsquared = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // tmp0 = r.x.square(); + c.call(f2mPrefix + "_square", Rx, t0), + + // tmp1 = r.y.square(); + c.call(f2mPrefix + "_square", Ry, t1), + + // tmp2 = tmp1.square(); + c.call(f2mPrefix + "_square", t1, t2), + + // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; + c.call(f2mPrefix + "_add", t1, Rx, t3), + c.call(f2mPrefix + "_square", t3, t3), + c.call(f2mPrefix + "_sub", t3, t0, t3), + c.call(f2mPrefix + "_sub", t3, t2, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp4 = tmp0 + tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t4), + c.call(f2mPrefix + "_add", t4, t0, t4), + + // tmp6 = r.x + tmp4; + c.call(f2mPrefix + "_add", Rx, t4, t6), + + // tmp5 = tmp4.square(); + c.call(f2mPrefix + "_square", t4, t5), + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // r.x = tmp5 - tmp3 - tmp3; + c.call(f2mPrefix + "_sub", t5, t3, Rx), + c.call(f2mPrefix + "_sub", Rx, t3, Rx), + + // r.z = (r.z + r.y).square() - tmp1 - zsquared; + c.call(f2mPrefix + "_add", Rz, Ry, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, t1, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + + // r.y = (tmp3 - r.x) * tmp4; + c.call(f2mPrefix + "_sub", t3, Rx, Ry), + c.call(f2mPrefix + "_mul", Ry, t4, Ry), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // r.y -= tmp2; + c.call(f2mPrefix + "_sub", Ry, t2, Ry), + + // tmp3 = tmp4 * zsquared; + c.call(f2mPrefix + "_mul", t4, zsquared, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp3 = -tmp3; + c.call(f2mPrefix + "_neg", t3, t3), + + // tmp6 = tmp6.square() - tmp0 - tmp5; + c.call(f2mPrefix + "_square", t6, t6), + c.call(f2mPrefix + "_sub", t6, t0, t6), + c.call(f2mPrefix + "_sub", t6, t5, t6), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp6 = tmp6 - tmp1; + c.call(f2mPrefix + "_sub", t6, t1, t6), + + // tmp0 = r.z * zsquared; + c.call(f2mPrefix + "_mul", Rz, zsquared, t0), + + // tmp0 = tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("R", "i32"); + f.addParam("Q", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const Qx = c.getLocal("Q"); + const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); + + const t10 = c.getLocal("r"); + const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + const zsquared = c.i32_const(module.alloc(f2size)); + const ysquared = c.i32_const(module.alloc(f2size)); + const ztsquared = c.i32_const(module.alloc(f2size)); + const t0 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const t6 = c.i32_const(module.alloc(f2size)); + const t7 = c.i32_const(module.alloc(f2size)); + const t8 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // ysquared = q.y.square(); + c.call(f2mPrefix + "_square", Qy, ysquared), + + // t0 = zsquared * q.x; + c.call(f2mPrefix + "_mul", zsquared, Qx, t0), + + // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; + c.call(f2mPrefix + "_add", Qy, Rz, t1), + c.call(f2mPrefix + "_square", t1, t1), + c.call(f2mPrefix + "_sub", t1, ysquared, t1), + c.call(f2mPrefix + "_sub", t1, zsquared, t1), + c.call(f2mPrefix + "_mul", t1, zsquared, t1), + + // t2 = t0 - r.x; + c.call(f2mPrefix + "_sub", t0, Rx, t2), + + // t3 = t2.square(); + c.call(f2mPrefix + "_square", t2, t3), + + // t4 = t3 + t3; + c.call(f2mPrefix + "_add", t3, t3, t4), + + // t4 = t4 + t4; + c.call(f2mPrefix + "_add", t4, t4, t4), + + // t5 = t4 * t2; + c.call(f2mPrefix + "_mul", t4, t2, t5), + + // t6 = t1 - r.y - r.y; + c.call(f2mPrefix + "_sub", t1, Ry, t6), + c.call(f2mPrefix + "_sub", t6, Ry, t6), + + // t9 = t6 * q.x; + c.call(f2mPrefix + "_mul", t6, Qx, t9), + + // t7 = t4 * r.x; + c.call(f2mPrefix + "_mul", t4, Rx, t7), + + // r.x = t6.square() - t5 - t7 - t7; + c.call(f2mPrefix + "_square", t6, Rx), + c.call(f2mPrefix + "_sub", Rx, t5, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + + // r.z = (r.z + t2).square() - zsquared - t3; + c.call(f2mPrefix + "_add", Rz, t2, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + c.call(f2mPrefix + "_sub", Rz, t3, Rz), + + // t10 = q.y + r.z; + c.call(f2mPrefix + "_add", Qy, Rz, t10), + + // t8 = (t7 - r.x) * t6; + c.call(f2mPrefix + "_sub", t7, Rx, t8), + c.call(f2mPrefix + "_mul", t8, t6, t8), + + // t0 = r.y * t5; + c.call(f2mPrefix + "_mul", Ry, t5, t0), + + // t0 = t0 + t0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + // r.y = t8 - t0; + c.call(f2mPrefix + "_sub", t8, t0, Ry), + + // t10 = t10.square() - ysquared; + c.call(f2mPrefix + "_square", t10, t10), + c.call(f2mPrefix + "_sub", t10, ysquared, t10), + + // ztsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, ztsquared), + + // t10 = t10 - ztsquared; + c.call(f2mPrefix + "_sub", t10, ztsquared, t10), + + // t9 = t9 + t9 - t10; + c.call(f2mPrefix + "_add", t9, t9, t9), + c.call(f2mPrefix + "_sub", t9, t10, t9), + + // t10 = r.z + r.z; + c.call(f2mPrefix + "_add", Rz, Rz, t10), + + // t6 = -t6; + c.call(f2mPrefix + "_neg", t6, t6), + + // t1 = t6 + t6; + c.call(f2mPrefix + "_add", t6, t6, t1), + ); + } + + + function buildPrepareG2() { + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + + const Q = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + + const base = c.getLocal("ppreQ"); + + f.addCode( + c.call(g2mPrefix + "_normalize", Q, base), + c.if( + c.call(g2mPrefix + "_isZero", base), + c.ret([]) + ), + c.call(g2mPrefix + "_copy", base, R), + c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), + ); + + f.addCode( + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildF6Mul1() { + const f = module.addFunction(f6mPrefix+ "_mul1"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue(); + c.call(f2mPrefix + "_mulNR", t1, t1), + + // let t2 = (self.c0 + self.c1) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + ); + } + buildF6Mul1(); + + function buildF6Mul01() { + const f = module.addFunction(f6mPrefix+ "_mul01"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const a_a = c.i32_const(module.alloc(f1size*2)); + const b_b = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + // let a_a = self.c0 * c0; + c.call(f2mPrefix + "_mul", A_c0, c0, a_a), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_add", A_c1, A_c2, t1), + c.call(f2mPrefix + "_mul", t1, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue() + a_a; + c.call(f2mPrefix + "_mulNR", t1, t1), + c.call(f2mPrefix + "_add", t1, a_a, t1), + + // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; + c.call(f2mPrefix + "_add", c0, c1, t2), + c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), + c.call(f2mPrefix + "_sub", t2, a_a, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + + // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), + c.call(f2mPrefix + "_sub", t3, a_a, t3), + c.call(f2mPrefix + "_add", t3, b_b, t3), + + + ); + } + buildF6Mul01(); + + + function buildF12Mul014() { + + const f = module.addFunction(ftmPrefix+ "_mul014"); + f.addParam("pA", "i32"); // F12 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pC4", "i32"); // F2 + f.addParam("pR", "i32"); // F12 + + const c = f.getCodeBuilder(); + + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + const c4 = c.getLocal("pC4"); + + const aa = c.i32_const(module.alloc(f1size*6)); + const bb = c.i32_const(module.alloc(f1size*6)); + const o = c.i32_const(module.alloc(f1size*2)); + + const R_c0 = c.getLocal("pR"); + const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); + + f.addCode( + // let aa = self.c0.mul_by_01(c0, c1); + c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), + + // let bb = self.c1.mul_by_1(c4); + c.call(f6mPrefix + "_mul1", A_c1, c4, bb), + + // let o = c1 + c4; + c.call(f2mPrefix + "_add", c1, c4, o), + + // let c1 = self.c1 + self.c0; + c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), + + // let c1 = c1.mul_by_01(c0, &o); + c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), + + // let c1 = c1 - aa - bb; + c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), + c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), + + // let c0 = bb; + c.call(f6mPrefix + "_copy", bb, R_c0), + + // let c0 = c0.mul_by_nonresidue(); + c.call(f6mPrefix + "_mulNR", R_c0, R_c0), + + // let c0 = c0 + aa; + c.call(f6mPrefix + "_add", R_c0, aa, R_c0), + ); + } + buildF12Mul014(); + + + function buildELL() { + const f = module.addFunction(prefix+ "_ell"); + f.addParam("pP", "i32"); + f.addParam("pCoefs", "i32"); + f.addParam("pF", "i32"); + + const c = f.getCodeBuilder(); + + const Px = c.getLocal("pP"); + const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); + + const F = c.getLocal("pF"); + + const coef0_0 = c.getLocal("pCoefs"); + const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); + const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); + const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); + const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); + + const pc0 = module.alloc(f1size*2); + const c0 = c.i32_const(pc0); + const c0_c0 = c.i32_const(pc0); + const c0_c1 = c.i32_const(pc0+f1size); + + const pc1 = module.alloc(f1size*2); + const c1 = c.i32_const(pc1); + const c1_c0 = c.i32_const(pc1); + const c1_c1 = c.i32_const(pc1+f1size); + f.addCode( + // let mut c0 = coeffs.0; + // let mut c1 = coeffs.1; + // + // c0.c0 *= p.y; + // c0.c1 *= p.y; + // + // c1.c0 *= p.x; + // c1.c1 *= p.x; + // + // f.mul_by_014(&coeffs.2, &c1, &c0) + + c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), + c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), + c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), + c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), + + c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), + + ); + + } + buildELL(); + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP = c.getLocal("ppreP"); + c.getLocal("ppreQ"); + + const coefs = c.getLocal("pCoef"); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.if( + c.call(g1mPrefix + "_isZero", preP), + c.ret([]) + ), + c.if( + c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), + c.ret([]) + ), + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(prefix + "_ell", preP, coefs, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_ell", preP, coefs, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.call(ftmPrefix + "_square", F, F), + + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + c.call(prefix + "_ell", preP, coefs, F), + + ); + + + { + f.addCode( + c.call(ftmPrefix + "_conjugate", F, F), + ); + } + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + ], + [ + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt$1("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], + [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt$1("0")], + [bigInt$1("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt$1("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], + [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], + [bigInt$1("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt$1("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], + [bigInt$1("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt$1("0")], + [bigInt$1("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt$1("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], + [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], + [bigInt$1("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt$1("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], + [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt$1("0")], + [bigInt$1("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt$1("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], + ] + ]; + + const F6 = [ + [ + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("1"), bigInt$1("0")], + ], + [ + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("0"), bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], + [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], + [bigInt$1("0"), bigInt$1("1")], + [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], + [bigInt$1("0"), bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], + ], + [ + [bigInt$1("1"), bigInt$1("0")], + [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt$1("0")], + [bigInt$1("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt$1("0")], + [bigInt$1("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt$1("0")], + [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt$1("0")], + [bigInt$1("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt$1("0")], + ] + ]; + + const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils$5.bigInt2BytesLE(toMontgomery(coef[0]), n8q), + ...utils$5.bigInt2BytesLE(toMontgomery(coef[1]), n8q), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt$1(a[0]); + const ac1 = bigInt$1(a[1]); + const bc0 = bigInt$1(b[0]); + const bc1 = bigInt$1(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mulNR", x1, t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mulNR", x3, t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mulNR", x5, t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, isExpNegative, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + if (isExpNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", res, res), + ); + } + + } + + function buildFinalExponentiation() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); + + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const res = c.getLocal("r"); + const t0 = c.i32_const(module.alloc(ftsize)); + const t1 = c.i32_const(module.alloc(ftsize)); + const t2 = c.i32_const(module.alloc(ftsize)); + const t3 = c.i32_const(module.alloc(ftsize)); + const t4 = c.i32_const(module.alloc(ftsize)); + const t5 = c.i32_const(module.alloc(ftsize)); + const t6 = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + // let mut t0 = f.frobenius_map(6) + c.call(ftmPrefix + "_frobeniusMap6", elt, t0), + + // let t1 = f.invert() + c.call(ftmPrefix + "_inverse", elt, t1), + + // let mut t2 = t0 * t1; + c.call(ftmPrefix + "_mul", t0, t1, t2), + + // t1 = t2.clone(); + c.call(ftmPrefix + "_copy", t2, t1), + + // t2 = t2.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t2, t2), + + // t2 *= t1; + c.call(ftmPrefix + "_mul", t2, t1, t2), + + + // t1 = cyclotomic_square(t2).conjugate(); + c.call(prefix + "__cyclotomicSquare", t2, t1), + c.call(ftmPrefix + "_conjugate", t1, t1), + + // let mut t3 = cycolotomic_exp(t2); + c.call(prefix + "__cyclotomicExp_w0", t2, t3), + + // let mut t4 = cyclotomic_square(t3); + c.call(prefix + "__cyclotomicSquare", t3, t4), + + // let mut t5 = t1 * t3; + c.call(ftmPrefix + "_mul", t1, t3, t5), + + // t1 = cycolotomic_exp(t5); + c.call(prefix + "__cyclotomicExp_w0", t5, t1), + + // t0 = cycolotomic_exp(t1); + c.call(prefix + "__cyclotomicExp_w0", t1, t0), + + // let mut t6 = cycolotomic_exp(t0); + c.call(prefix + "__cyclotomicExp_w0", t0, t6), + + // t6 *= t4; + c.call(ftmPrefix + "_mul", t6, t4, t6), + + // t4 = cycolotomic_exp(t6); + c.call(prefix + "__cyclotomicExp_w0", t6, t4), + + // t5 = t5.conjugate(); + c.call(ftmPrefix + "_conjugate", t5, t5), + + // t4 *= t5 * t2; + c.call(ftmPrefix + "_mul", t4, t5, t4), + c.call(ftmPrefix + "_mul", t4, t2, t4), + + // t5 = t2.conjugate(); + c.call(ftmPrefix + "_conjugate", t2, t5), + + // t1 *= t2; + c.call(ftmPrefix + "_mul", t1, t2, t1), + + // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap3", t1, t1), + + // t6 *= t5; + c.call(ftmPrefix + "_mul", t6, t5, t6), + + // t6 = t6.frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap1", t6, t6), + + // t3 *= t0; + c.call(ftmPrefix + "_mul", t3, t0, t3), + + // t3 = t3.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t3, t3), + + // t3 *= t1; + c.call(ftmPrefix + "_mul", t3, t1, t3), + + // t3 *= t6; + c.call(ftmPrefix + "_mul", t3, t6, t3), + + // f = t3 * t4; + c.call(ftmPrefix + "_mul", t3, t4, res), + + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt$1("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); + + const pExponent = module.alloc(utils$5.bigInt2BytesLE( exponent, 544 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), + ); + } + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i. +*/ + +// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); +// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); +// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); + +var buildBn128$1 = build_bn128; +var buildBls12381$1 = build_bls12381; + +/* global BigInt */ + +function stringifyBigInts$2(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return fromRprLE(o, 0); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts$2); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyBigInts$2(o[k]); + }); + return res; + } else { + return o; + } +} + +function unstringifyBigInts$2(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return BigInt(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return BigInt(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts$2); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyBigInts$2(o[k]); + }); + return res; + } else { + return o; + } +} + +function beBuff2int$2(buff) { + let res = BigInt(0); + let i = buff.length; + let offset = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i>0) { + if (i >= 4) { + i -= 4; + res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); + offset += 4; + } else if (i >= 2) { + i -= 2; + res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); + offset += 2; + } else { + i -= 1; + res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); + offset += 1; + } + } + return res; +} + +function beInt2Buff$2(n, len) { + let r = n; + const buff = new Uint8Array(len); + const buffV = new DataView(buff.buffer); + let o = len; + while (o > 0) { + if (o-4 >= 0) { + o -= 4; + buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); + r = r >> BigInt(32); + } else if (o-2 >= 0) { + o -= 2; + buffV.setUint16(o, Number(r & BigInt(0xFFFF))); + r = r >> BigInt(16); + } else { + o -= 1; + buffV.setUint8(o, Number(r & BigInt(0xFF))); + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function leBuff2int$2(buff) { + let res = BigInt(0); + let i = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i> BigInt(32); + } else if (o+2 <= len) { + buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); + o += 2; + r = r >> BigInt(16); + } else { + buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); + o += 1; + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function stringifyFElements$1(F, o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return F.toString(F.e(o)); + } else if (Array.isArray(o)) { + return o.map(stringifyFElements$1.bind(this,F)); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyFElements$1(F, o[k]); + }); + return res; + } else { + return o; + } +} + + +function unstringifyFElements$1(F, o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return F.e(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return F.e(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyFElements$1.bind(this,F)); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyFElements$1(F, o[k]); + }); + return res; + } else { + return o; + } +} + +var utils_native = /*#__PURE__*/Object.freeze({ + __proto__: null, + beBuff2int: beBuff2int$2, + beInt2Buff: beInt2Buff$2, + leBuff2int: leBuff2int$2, + leInt2Buff: leInt2Buff$2, + stringifyBigInts: stringifyBigInts$2, + stringifyFElements: stringifyFElements$1, + unstringifyBigInts: unstringifyBigInts$2, + unstringifyFElements: unstringifyFElements$1 +}); + +function stringifyBigInts$1(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts$1); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyBigInts$1(o[k]); + }); + return res; + } else { + return o; + } +} + +function unstringifyBigInts$1(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return bigInt$8(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return bigInt$8(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts$1); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyBigInts$1(o[k]); + }); + return res; + } else { + return o; + } +} + +function beBuff2int$1(buff) { + let res = bigInt$8.zero; + for (let i=0; i=0)) { + let c = Number(r.and(bigInt$8("255"))); + buff[o] = c; + o--; + r = r.shiftRight(8); + } + if (!r.eq(bigInt$8.zero)) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function leBuff2int$1 (buff) { + let res = bigInt$8.zero; + for (let i=0; i>=1; + } + return res; +} + +utils$4.bitReverse = function bitReverse(idx, bits) { + return ( + _revTable[idx >>> 24] | + (_revTable[(idx >>> 16) & 0xFF] << 8) | + (_revTable[(idx >>> 8) & 0xFF] << 16) | + (_revTable[idx & 0xFF] << 24) + ) >>> (32-bits); +}; + + +utils$4.log2 = function log2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +}; + +utils$4.buffReverseBits = function buffReverseBits(buff, eSize) { + const n = buff.byteLength /eSize; + const bits = utils$4.log2(n); + if (n != (1 << bits)) { + throw new Error("Invalid number of pointers"); + } + for (let i=0; ir) { + const tmp = buff.slice(i*eSize, (i+1)*eSize); + buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); + buff.set(tmp, r*eSize); + } + } +}; + + +utils$4.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i0) { + // bytes to copy from this page + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset+o, l); + if (l == len) return srcView.slice(); + if (!buff) { + if (len <= PAGE_SIZE) { + buff = new Uint8Array(len); + } else { + buff = new BigBuffer(len); + } + } + buff.set(srcView, len-r); + r = r-l; + p ++; + o = 0; + } + + return buff; + } + + set(buff, offset) { + if (offset === undefined) offset = 0; + + const len = buff.byteLength; + + if (len==0) return; + + const firstPage = Math.floor(offset / PAGE_SIZE); + const lastPage = Math.floor((offset+len-1) / PAGE_SIZE); + + if (firstPage == lastPage) { + if ((buff instanceof BigBuffer)&&(buff.buffers.length==1)) { + return this.buffers[firstPage].set(buff.buffers[0], offset % PAGE_SIZE); + } else { + return this.buffers[firstPage].set(buff, offset % PAGE_SIZE); + } + + } + + + let p = firstPage; + let o = offset % PAGE_SIZE; + let r = len; + while (r>0) { + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = buff.slice( len -r, len -r+l); + const dstView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset + o, l); + dstView.set(srcView); + r = r-l; + p ++; + o = 0; + } + + } +} + +function buildBatchConvert(tm, fnName, sIn, sOut) { + return async function batchConvert(buffIn) { + const nPoints = Math.floor(buffIn.byteLength / sIn); + if ( nPoints * sIn !== buffIn.byteLength) { + throw new Error("Invalid buffer size"); + } + const pointsPerChunk = Math.floor(nPoints/tm.concurrency); + const opPromises = []; + for (let i=0; i=0; i--) { + this.w[i] = this.square(this.w[i+1]); + } + + if (!this.eq(this.w[0], this.one)) { + throw new Error("Error calculating roots of unity"); + } + + this.batchToMontgomery = buildBatchConvert(tm, prefix + "_batchToMontgomery", this.n8, this.n8); + this.batchFromMontgomery = buildBatchConvert(tm, prefix + "_batchFromMontgomery", this.n8, this.n8); + } + + + op2(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op2Bool(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2); + } + + op1(opName, a) { + this.tm.setBuff(this.pOp1, a); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op1Bool(opName, a) { + this.tm.setBuff(this.pOp1, a); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + } + + add(a,b) { + return this.op2("_add", a, b); + } + + + eq(a,b) { + return this.op2Bool("_eq", a, b); + } + + isZero(a) { + return this.op1Bool("_isZero", a); + } + + sub(a,b) { + return this.op2("_sub", a, b); + } + + neg(a) { + return this.op1("_neg", a); + } + + inv(a) { + return this.op1("_inverse", a); + } + + toMontgomery(a) { + return this.op1("_toMontgomery", a); + } + + fromMontgomery(a) { + return this.op1("_fromMontgomery", a); + } + + mul(a,b) { + return this.op2("_mul", a, b); + } + + div(a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_inverse"](this.pOp2, this.pOp2); + this.tm.instance.exports[this.prefix + "_mul"](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + square(a) { + return this.op1("_square", a); + } + + isSquare(a) { + return this.op1Bool("_isSquare", a); + } + + sqrt(a) { + return this.op1("_sqrt", a); + } + + exp(a, b) { + if (!(b instanceof Uint8Array)) { + b = toLEBuff(e(b)); + } + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_exp"](this.pOp1, this.pOp2, b.byteLength, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + isNegative(a) { + return this.op1Bool("_isNegative", a); + } + + e(a, b) { + if (a instanceof Uint8Array) return a; + let ra = e(a, b); + if (isNegative(ra)) { + ra = neg(ra); + if (gt(ra, this.p)) { + ra = mod(ra, this.p); + } + ra = sub(this.p, ra); + } else { + if (gt(ra, this.p)) { + ra = mod(ra, this.p); + } + } + const buff = leInt2Buff(ra, this.n8); + return this.toMontgomery(buff); + } + + toString(a, radix) { + const an = this.fromMontgomery(a); + const s = fromRprLE(an, 0); + return toString(s, radix); + } + + fromRng(rng) { + let v; + const buff = new Uint8Array(this.n8); + do { + v = zero; + for (let i=0; i memory.buffer.byteLength) { + const currentPages = memory.buffer.byteLength / 0x10000; + let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1; + if (requiredPages>MAXMEM) requiredPages=MAXMEM; + memory.grow(requiredPages-currentPages); + } + return res; + } + + function allocBuffer(buffer) { + const p = alloc(buffer.byteLength); + setBuffer(p, buffer); + return p; + } + + function getBuffer(pointer, length) { + const u8 = new Uint8Array(memory.buffer); + return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length); + } + + function setBuffer(pointer, buffer) { + const u8 = new Uint8Array(memory.buffer); + u8.set(new Uint8Array(buffer), pointer); + } + + function runTask(task) { + if (task[0].cmd == "INIT") { + return init(task[0]); + } + const ctx = { + vars: [], + out: [] + }; + const u32a = new Uint32Array(memory.buffer, 0, 1); + const oldAlloc = u32a[0]; + for (let i=0; i { + try { + handler.call(this, event); + } + catch (err) { + console.error(err); + } + }); + } + addEventListener(type, fn) { + let events = this[EVENTS].get(type); + if (!events) this[EVENTS].set(type, events = []); + events.push(fn); + } + removeEventListener(type, fn) { + let events = this[EVENTS].get(type); + if (events) { + const index = events.indexOf(fn); + if (index !== -1) events.splice(index, 1); + } + } +} + +function Event(type, target) { + this.type = type; + this.timeStamp = Date.now(); + this.target = this.currentTarget = this.data = null; +} + +// this module is used self-referentially on both sides of the +// thread boundary, but behaves differently in each context. +var Worker = threads.isMainThread ? mainThread() : workerThread(); + +const baseUrl = URL.pathToFileURL(process.cwd() + '/'); + +function mainThread() { + + /** + * A web-compatible Worker implementation atop Node's worker_threads. + * - uses DOM-style events (Event.data, Event.type, etc) + * - supports event handler properties (worker.onmessage) + * - Worker() constructor accepts a module URL + * - accepts the {type:'module'} option + * - emulates WorkerGlobalScope within the worker + * @param {string} url The URL or module specifier to load + * @param {object} [options] Worker construction options + * @param {string} [options.name] Available as `self.name` within the Worker + * @param {string} [options.type="classic"] Pass "module" to create a Module Worker. + */ + class Worker extends EventTarget { + constructor(url, options) { + super(); + const { name, type } = options || {}; + url += ''; + let mod; + if (/^data:/.test(url)) { + mod = url; + } + else { + mod = URL.fileURLToPath(new URL.URL(url, baseUrl)); + } + const worker = new threads.Worker( + __filename, + { workerData: { mod, name, type } } + ); + Object.defineProperty(this, WORKER, { + value: worker + }); + worker.on('message', data => { + const event = new Event('message'); + event.data = data; + this.dispatchEvent(event); + }); + worker.on('error', error => { + error.type = 'error'; + this.dispatchEvent(error); + }); + worker.on('exit', () => { + this.dispatchEvent(new Event('close')); + }); + } + postMessage(data, transferList) { + this[WORKER].postMessage(data, transferList); + } + terminate() { + this[WORKER].terminate(); + } + } + Worker.prototype.onmessage = Worker.prototype.onerror = Worker.prototype.onclose = null; + return Worker; +} + +function workerThread() { + let { mod, name, type } = threads.workerData; + if (!mod) return mainThread(); + + // turn global into a mock WorkerGlobalScope + const self = global.self = global; + + // enqueue messages to dispatch after modules are loaded + let q = []; + function flush() { + const buffered = q; + q = null; + buffered.forEach(event => { self.dispatchEvent(event); }); + } + threads.parentPort.on('message', data => { + const event = new Event('message'); + event.data = data; + if (q == null) self.dispatchEvent(event); + else q.push(event); + }); + threads.parentPort.on('error', err => { + err.type = 'Error'; + self.dispatchEvent(err); + }); + + class WorkerGlobalScope extends EventTarget { + postMessage(data, transferList) { + threads.parentPort.postMessage(data, transferList); + } + // Emulates https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/close + close() { + process.exit(); + } + } + let proto = Object.getPrototypeOf(global); + delete proto.constructor; + Object.defineProperties(WorkerGlobalScope.prototype, proto); + proto = Object.setPrototypeOf(global, new WorkerGlobalScope()); + ['postMessage', 'addEventListener', 'removeEventListener', 'dispatchEvent'].forEach(fn => { + proto[fn] = proto[fn].bind(global); + }); + global.name = name; + + const isDataUrl = /^data:/.test(mod); + if (type === 'module') { + import(mod) + .catch(err => { + if (isDataUrl && err.message === 'Not supported') { + console.warn('Worker(): Importing data: URLs requires Node 12.10+. Falling back to classic worker.'); + return evaluateDataUrl(mod, name); + } + console.error(err); + }) + .then(flush); + } + else { + try { + if (/^data:/.test(mod)) { + evaluateDataUrl(mod, name); + } + else { + require(mod); + } + } + catch (err) { + console.error(err); + } + Promise.resolve().then(flush); + } +} + +function evaluateDataUrl(url, name) { + const { data } = parseDataUrl(url); + return VM.runInThisContext(data, { + filename: 'worker.<'+(name || 'data:')+'>' + }); +} + +function parseDataUrl(url) { + let [m, type, encoding, data] = url.match(/^data: *([^;,]*)(?: *; *([^,]*))? *,(.*)$/) || []; + if (!m) throw Error('Invalid Data URL.'); + if (encoding) switch (encoding.toLowerCase()) { + case 'base64': + data = Buffer.from(data, 'base64').toString(); + break; + default: + throw Error('Unknown Data URL encoding "' + encoding + '"'); + } + return { type, data }; +} + +/* global navigator, WebAssembly */ +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +// const MEM_SIZE = 1000; // Memory size in 64K Pakes (512Mb) +const MEM_SIZE = 25; // Memory size in 64K Pakes (1600Kb) + +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject)=> { + this.reject = reject; + this.resolve = resolve; + }); + } +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function stringToBase64(str) { + if (process.browser) { + return globalThis.btoa(str); + } else { + return Buffer.from(str).toString("base64"); + } +} + +const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); +const workerSource = "data:application/javascript;base64," + threadSource; + + + +async function buildThreadManager(wasm, singleThread) { + const tm = new ThreadManager(); + + tm.memory = new WebAssembly.Memory({initial:MEM_SIZE}); + tm.u8 = new Uint8Array(tm.memory.buffer); + tm.u32 = new Uint32Array(tm.memory.buffer); + + const wasmModule = await WebAssembly.compile(wasm.code); + + tm.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": tm.memory + } + }); + + tm.singleThread = singleThread; + tm.initalPFree = tm.u32[0]; // Save the Pointer to free space. + tm.pq = wasm.pq; + tm.pr = wasm.pr; + tm.pG1gen = wasm.pG1gen; + tm.pG1zero = wasm.pG1zero; + tm.pG2gen = wasm.pG2gen; + tm.pG2zero = wasm.pG2zero; + tm.pOneT = wasm.pOneT; + + // tm.pTmp0 = tm.alloc(curve.G2.F.n8*3); + // tm.pTmp1 = tm.alloc(curve.G2.F.n8*3); + + + if (singleThread) { + tm.code = wasm.code; + tm.taskManager = thread(); + await tm.taskManager([{ + cmd: "INIT", + init: MEM_SIZE, + code: tm.code.slice() + }]); + tm.concurrency = 1; + } else { + tm.workers = []; + tm.pendingDeferreds = []; + tm.working = []; + + let concurrency; + + if ((typeof(navigator) === "object") && navigator.hardwareConcurrency) { + concurrency = navigator.hardwareConcurrency; + } else { + concurrency = os.cpus().length; + } + + if(concurrency == 0){ + concurrency = 2; + } + + // Limit to 64 threads for memory reasons. + if (concurrency>64) concurrency=64; + tm.concurrency = concurrency; + + for (let i = 0; i 0); i++) { + if (this.working[i] == false) { + const work = this.actionQueue.shift(); + this.postAction(i, work.data, work.transfers, work.deferred); + } + } + } + + queueAction(actionData, transfers) { + const d = new Deferred(); + + if (this.singleThread) { + const res = this.taskManager(actionData); + d.resolve(res); + } else { + this.actionQueue.push({ + data: actionData, + transfers: transfers, + deferred: d + }); + this.processWorks(); + } + return d.promise; + } + + resetMemory() { + this.u32[0] = this.initalPFree; + } + + allocBuff(buff) { + const pointer = this.alloc(buff.byteLength); + this.setBuff(pointer, buff); + return pointer; + } + + getBuff(pointer, length) { + return this.u8.slice(pointer, pointer+ length); + } + + setBuff(pointer, buffer) { + this.u8.set(new Uint8Array(buffer), pointer); + } + + alloc(length) { + while (this.u32[0] & 3) this.u32[0]++; // Return always aligned pointers + const res = this.u32[0]; + this.u32[0] += length; + return res; + } + + async terminate() { + for (let i=0; i=0; i--) { + if (!G.isZero(res)) { + for (let j=0; jMAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + if (chunkSize { + if (logger) logger.debug(`Multiexp end: ${logText}: ${i}/${nPoints}`); + return r; + })); + } + + const result = await Promise.all(opPromises); + + let res = G.zero; + for (let i=result.length-1; i>=0; i--) { + res = G.add(res, result[i]); + } + + return res; + } + + G.multiExp = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "jacobian", logger, logText); + }; + G.multiExpAffine = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "affine", logger, logText); + }; +} + +function buildFFT(curve, groupName) { + const G = curve[groupName]; + const Fr = curve.Fr; + const tm = G.tm; + async function _fft(buff, inverse, inType, outType, logger, loggerTxt) { + + inType = inType || "affine"; + outType = outType || "affine"; + const MAX_BITS_THREAD = 14; + + let sIn, sMid, sOut, fnIn2Mid, fnMid2Out, fnFFTMix, fnFFTJoin, fnFFTFinal; + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g1m_fftFinal"; + } + fnFFTJoin = "g1m_fftJoin"; + fnFFTMix = "g1m_fftMix"; + + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g1m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g2m_fftFinal"; + } + fnFFTJoin = "g2m_fftJoin"; + fnFFTMix = "g2m_fftMix"; + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g2m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = G.n8; + sMid = G.n8; + sOut = G.n8; + if (inverse) { + fnFFTFinal = "frm_fftFinal"; + } + fnFFTMix = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } + + + let returnArray = false; + if (Array.isArray(buff)) { + buff = array2buffer(buff, sIn); + returnArray = true; + } else { + buff = buff.slice(0, buff.byteLength); + } + + const nPoints = buff.byteLength / sIn; + const bits = log2(nPoints); + + if ((1 << bits) != nPoints) { + throw new Error("fft must be multiple of 2" ); + } + + if (bits == Fr.s +1) { + let buffOut; + + if (inverse) { + buffOut = await _fftExtInv(buff, inType, outType, logger, loggerTxt); + } else { + buffOut = await _fftExt(buff, inType, outType, logger, loggerTxt); + } + + if (returnArray) { + return buffer2array(buffOut, sOut); + } else { + return buffOut; + } + } + + let inv; + if (inverse) { + inv = Fr.inv(Fr.e(nPoints)); + } + + let buffOut; + + buffReverseBits(buff, sIn); + + let chunks; + let pointsInChunk = Math.min(1 << MAX_BITS_THREAD, nPoints); + let nChunks = nPoints / pointsInChunk; + + while ((nChunks < tm.concurrency)&&(pointsInChunk>=16)) { + nChunks *= 2; + pointsInChunk /= 2; + } + + const l2Chunk = log2(pointsInChunk); + + const promises = []; + for (let i = 0; i< nChunks; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix start: ${i}/${nChunks}`); + const task = []; + task.push({cmd: "ALLOC", var: 0, len: sMid*pointsInChunk}); + const buffChunk = buff.slice( (pointsInChunk * i)*sIn, (pointsInChunk * (i+1))*sIn); + task.push({cmd: "SET", var: 0, buff: buffChunk}); + if (fnIn2Mid) { + task.push({cmd: "CALL", fnName:fnIn2Mid, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + for (let j=1; j<=l2Chunk;j++) { + task.push({cmd: "CALL", fnName:fnFFTMix, params: [{var:0}, {val: pointsInChunk}, {val: j}]}); + } + + if (l2Chunk==bits) { + if (fnFFTFinal) { + task.push({cmd: "ALLOCSET", var: 1, buff: inv}); + task.push({cmd: "CALL", fnName: fnFFTFinal, params:[ + {var: 0}, + {val: pointsInChunk}, + {var: 1}, + ]}); + } + if (fnMid2Out) { + task.push({cmd: "CALL", fnName:fnMid2Out, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + task.push({cmd: "GET", out: 0, var: 0, len: pointsInChunk*sOut}); + } else { + task.push({cmd: "GET", out:0, var: 0, len: sMid*pointsInChunk}); + } + promises.push(tm.queueAction(task).then( (r) => { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix end: ${i}/${nChunks}`); + return r; + })); + } + + chunks = await Promise.all(promises); + for (let i = 0; i< nChunks; i++) chunks[i] = chunks[i][0]; + + for (let i = l2Chunk+1; i<=bits; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join: ${i}/${bits}`); + const nGroups = 1 << (bits - i); + const nChunksPerGroup = nChunks / nGroups; + const opPromises = []; + for (let j=0; j { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join ${i}/${bits} ${j+1}/${nGroups} ${k}/${nChunksPerGroup/2}`); + return r; + })); + } + } + + const res = await Promise.all(opPromises); + for (let j=0; j0; i--) { + buffOut.set(chunks[i], p); + p += pointsInChunk*sOut; + delete chunks[i]; // Liberate mem + } + buffOut.set(chunks[0].slice(0, (pointsInChunk-1)*sOut), p); + delete chunks[0]; + } else { + for (let i=0; i (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + async function _fftExtInv(buff, inType, outType, logger, loggerTxt) { + let b1, b2; + b1 = buff.slice( 0 , buff.byteLength/2); + b2 = buff.slice( buff.byteLength/2, buff.byteLength); + + const promises = []; + + promises.push( _fft(b1, true, inType, "jacobian", logger, loggerTxt)); + promises.push( _fft(b2, true, inType, "jacobian", logger, loggerTxt)); + + [b1, b2] = await Promise.all(promises); + + const res1 = await _fftJoinExt(b1, b2, "fftJoinExtInv", Fr.one, Fr.shiftInv, "jacobian", outType, logger, loggerTxt); + + let buffOut; + if (res1[0].byteLength > (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + + async function _fftJoinExt(buff1, buff2, fn, first, inc, inType, outType, logger, loggerTxt) { + const MAX_CHUNK_SIZE = 1<<16; + const MIN_CHUNK_SIZE = 1<<4; + + let fnName; + let fnIn2Mid, fnMid2Out; + let sOut, sIn, sMid; + + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + fnName = "g1m_"+fn; + if (outType == "affine") { + fnMid2Out = "g1m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + fnName = "g2m_"+fn; + sMid = G.F.n8*3; + if (outType == "affine") { + fnMid2Out = "g2m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = Fr.n8; + sOut = Fr.n8; + sMid = Fr.n8; + fnName = "frm_" + fn; + } else { + throw new Error("Invalid group"); + } + + if (buff1.byteLength != buff2.byteLength) { + throw new Error("Invalid buffer size"); + } + const nPoints = Math.floor(buff1.byteLength / sIn); + if (nPoints != 1 << log2(nPoints)) { + throw new Error("Invalid number of points"); + } + + let chunkSize = Math.floor(nPoints /tm.concurrency); + if (chunkSize < MIN_CHUNK_SIZE) chunkSize = MIN_CHUNK_SIZE; + if (chunkSize > MAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + + const opPromises = []; + + for (let i=0; i { + if (logger) logger.debug(`${loggerTxt}: fftJoinExt End: ${i}/${nPoints}`); + return r; + }) + ); + } + + const result = await Promise.all(opPromises); + + let fullBuffOut1; + let fullBuffOut2; + if (nPoints * sOut > 1<<28) { + fullBuffOut1 = new BigBuffer(nPoints*sOut); + fullBuffOut2 = new BigBuffer(nPoints*sOut); + } else { + fullBuffOut1 = new Uint8Array(nPoints*sOut); + fullBuffOut2 = new Uint8Array(nPoints*sOut); + } + + let p =0; + for (let i=0; i Fr.s+1) { + if (logger) logger.error("lagrangeEvaluations input too big"); + throw new Error("lagrangeEvaluations input too big"); + } + + let t0 = buff.slice(0, buff.byteLength/2); + let t1 = buff.slice(buff.byteLength/2, buff.byteLength); + + + const shiftToSmallM = Fr.exp(Fr.shift, nPoints/2); + const sConst = Fr.inv( Fr.sub(Fr.one, shiftToSmallM)); + + [t0, t1] = await _fftJoinExt(t0, t1, "prepareLagrangeEvaluation", sConst, Fr.shiftInv, inType, "jacobian", logger, loggerTxt + " prep"); + + const promises = []; + + promises.push( _fft(t0, true, "jacobian", outType, logger, loggerTxt + " t0")); + promises.push( _fft(t1, true, "jacobian", outType, logger, loggerTxt + " t1")); + + [t0, t1] = await Promise.all(promises); + + let buffOut; + if (t0.byteLength > (1<<28)) { + buffOut = new BigBuffer(t0.byteLength*2); + } else { + buffOut = new Uint8Array(t0.byteLength*2); + } + + buffOut.set(t0); + buffOut.set(t1, t0.byteLength); + + return buffOut; + }; + + G.fftMix = async function fftMix(buff) { + const sG = G.F.n8*3; + let fnName, fnFFTJoin; + if (groupName == "G1") { + fnName = "g1m_fftMix"; + fnFFTJoin = "g1m_fftJoin"; + } else if (groupName == "G2") { + fnName = "g2m_fftMix"; + fnFFTJoin = "g2m_fftJoin"; + } else if (groupName == "Fr") { + fnName = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } else { + throw new Error("Invalid group"); + } + + const nPoints = Math.floor(buff.byteLength / sG); + const power = log2(nPoints); + + let nChunks = 1 << log2(tm.concurrency); + + if (nPoints <= nChunks*2) nChunks = 1; + + const pointsPerChunk = nPoints / nChunks; + + const powerChunk = log2(pointsPerChunk); + + const opPromises = []; + for (let i=0; i=0; i--) { + fullBuffOut.set(result[i][0], p); + p+=result[i][0].byteLength; + } + + return fullBuffOut; + }; +} + +async function buildEngine(params) { + + const tm = await buildThreadManager(params.wasm, params.singleThread); + + + const curve = {}; + + curve.q = e(params.wasm.q); + curve.r = e(params.wasm.r); + curve.name = params.name; + curve.tm = tm; + curve.prePSize = params.wasm.prePSize; + curve.preQSize = params.wasm.preQSize; + curve.Fr = new WasmField1(tm, "frm", params.n8r, params.r); + curve.F1 = new WasmField1(tm, "f1m", params.n8q, params.q); + curve.F2 = new WasmField2(tm, "f2m", curve.F1); + curve.G1 = new WasmCurve(tm, "g1m", curve.F1, params.wasm.pG1gen, params.wasm.pG1b, params.cofactorG1); + curve.G2 = new WasmCurve(tm, "g2m", curve.F2, params.wasm.pG2gen, params.wasm.pG2b, params.cofactorG2); + curve.F6 = new WasmField3(tm, "f6m", curve.F2); + curve.F12 = new WasmField2(tm, "ftm", curve.F6); + + curve.Gt = curve.F12; + + buildBatchApplyKey(curve, "G1"); + buildBatchApplyKey(curve, "G2"); + buildBatchApplyKey(curve, "Fr"); + + buildMultiexp(curve, "G1"); + buildMultiexp(curve, "G2"); + + buildFFT(curve, "G1"); + buildFFT(curve, "G2"); + buildFFT(curve, "Fr"); + + buildPairing(curve); + + curve.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i. +*/ + +const bigInt = BigIntegerExports; + +function toNumber(n) { + let v; + if (typeof n=="string") { + if (n.slice(0,2).toLowerCase() == "0x") { + v = bigInt(n.slice(2),16); + } else { + v = bigInt(n); + } + } else { + v = bigInt(n); + } + return v; +} + +function u32(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + return b; +} + +function u64(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + b.push(v.shiftRight(32).and(0xFF).toJSNumber()); + b.push(v.shiftRight(40).and(0xFF).toJSNumber()); + b.push(v.shiftRight(48).and(0xFF).toJSNumber()); + b.push(v.shiftRight(56).and(0xFF).toJSNumber()); + return b; +} + +function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; +} + +function string(str) { + const bytes = toUTF8Array(str); + return [ ...varuint32(bytes.length), ...bytes ]; +} + +function varuint(n) { + const code = []; + let v = toNumber(n); + if (v.isNegative()) throw new Error("Number cannot be negative"); + while (!v.isZero()) { + code.push(v.and(0x7F).toJSNumber()); + v = v.shiftRight(7); + } + if (code.length==0) code.push(0); + for (let i=0; i. +*/ + +const utils$2 = utils$3; + +let CodeBuilder$1 = class CodeBuilder { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x21, ...utils$2.varuint32( idx )]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x22, ...utils$2.varuint32( idx )]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [0x20, ...utils$2.varuint32( idx )]; + } + + i64_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x30, align, ...utils$2.varuint32(offset)]; + } + + i64_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x31, align, ...utils$2.varuint32(offset)]; + } + + i64_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x32, align, ...utils$2.varuint32(offset)]; + } + + i64_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x33, align, ...utils$2.varuint32(offset)]; + } + + i64_load32_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x34, align, ...utils$2.varuint32(offset)]; + } + + i64_load32_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x35, align, ...utils$2.varuint32(offset)]; + } + + i64_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default + return [...idxCode, 0x29, align, ...utils$2.varuint32(offset)]; + } + + + i64_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 3; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 3; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x37, align, ...utils$2.varuint32(offset)]; + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3e, align, ...utils$2.varuint32(offset)]; + } + + + i64_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3d, align, ...utils$2.varuint32(offset)]; + } + + + i64_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3c, align, ...utils$2.varuint32(offset)]; + } + + i32_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2c, align, ...utils$2.varuint32(offset)]; + } + + i32_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2d, align, ...utils$2.varuint32(offset)]; + } + + i32_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2e, align, ...utils$2.varuint32(offset)]; + } + + i32_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2f, align, ...utils$2.varuint32(offset)]; + } + + i32_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x28, align, ...utils$2.varuint32(offset)]; + } + + i32_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x36, align, ...utils$2.varuint32(offset)]; + } + + + i32_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3b, align, ...utils$2.varuint32(offset)]; + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3a, align, ...utils$2.varuint32(offset)]; + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [...[].concat(...args), 0x10, ...utils$2.varuint32(idx)]; + } + + call_indirect(fnIdx, ...args) { + return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; + } else { + return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; + } + } + + block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } + loop(...args) { + return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; + } + br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils$2.varuint32(relPath)]; } + br(relPath) { return [0x0c, ...utils$2.varuint32(relPath)]; } + ret(rCode) { return [...rCode, 0x0f]; } + drop(dCode) { return [...dCode, 0x1a]; } + + i64_const(num) { return [0x42, ...utils$2.varint64(num)]; } + i32_const(num) { return [0x41, ...utils$2.varint32(num)]; } + + + i64_eqz(opcode) { return [...opcode, 0x50]; } + i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } + i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } + i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } + i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } + i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } + i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } + i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } + i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } + i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } + i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } + i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } + i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } + i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } + i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } + i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } + i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } + i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } + i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } + i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } + i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } + i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } + i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } + i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } + i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } + i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } + i64_clz(op1code) { return [...op1code, 0x79]; } + i64_ctz(op1code) { return [...op1code, 0x7a]; } + + i32_eqz(op1code) { return [...op1code, 0x45]; } + i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } + i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } + i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } + i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } + i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } + i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } + i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } + i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } + i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } + i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } + i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } + i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } + i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } + i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } + i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } + i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } + i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } + i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } + i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } + i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } + i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } + i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } + i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } + i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } + i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } + i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } + i32_clz(op1code) { return [...op1code, 0x67]; } + i32_ctz(op1code) { return [...op1code, 0x68]; } + + unreachable() { return [ 0x0 ]; } + + current_memory() { return [ 0x3f, 0]; } + + comment() { return []; } +}; + +var codebuilder = CodeBuilder$1; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const CodeBuilder = codebuilder; +const utils$1 = utils$3; + +const typeCodes = { + "i32": 0x7f, + "i64": 0x7e, + "f32": 0x7d, + "f64": 0x7c, + "anyfunc": 0x70, + "func": 0x60, + "emptyblock": 0x40 +}; + + +let FunctionBuilder$1 = class FunctionBuilder { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType + }); + } + + addLocal(localName, localType, _length) { + const length = _length || 1; + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + length: length + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + const params = [...utils$1.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; + const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; + return [0x60, ...params, ...returns]; + } + + getBody() { + const locals = this.locals.map((l) => [ + ...utils$1.varuint32(l.length), + typeCodes[l.type] + ]); + + const body = [ + ...utils$1.varuint32(this.locals.length), + ...[].concat(...locals), + ...this.code, + 0x0b + ]; + return [ + ...utils$1.varuint32(body.length), + ...body + ]; + } + + addCode(...code) { + this.code.push(...[].concat(...[...code])); + } + + getCodeBuilder() { + return new CodeBuilder(this); + } +}; + +var functionbuilder = FunctionBuilder$1; + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const FunctionBuilder = functionbuilder; +const utils = utils$3; + +let ModuleBuilder$1 = class ModuleBuilder { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + this._setSignatures(); + return new Uint8Array([ + ...utils.u32(0x6d736100), + ...utils.u32(1), + ...this._buildType(), + ...this._buildImport(), + ...this._buildFunctionDeclarations(), + ...this._buildFunctionsTable(), + ...this._buildExports(), + ...this._buildElements(), + ...this._buildCode(), + ...this._buildData() + ]); + } + + addFunction(fnName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "internal")); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new globalThis.TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = "s_"+utils.toHexString(signature); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i. +*/ + +var ModuleBuilder = modulebuilder; + +globalThis.curve_bn128 = null; + +async function buildBn128(singleThread, plugins) { + + const moduleBuilder = new ModuleBuilder(); + moduleBuilder.setMemory(25); + buildBn128$1(moduleBuilder); + + if (plugins) plugins(moduleBuilder); + + const bn128wasm = {}; + + bn128wasm.code = moduleBuilder.build(); + bn128wasm.pq = moduleBuilder.modules.f1m.pq; + bn128wasm.pr = moduleBuilder.modules.frm.pq; + bn128wasm.pG1gen = moduleBuilder.modules.bn128.pG1gen; + bn128wasm.pG1zero = moduleBuilder.modules.bn128.pG1zero; + bn128wasm.pG1b = moduleBuilder.modules.bn128.pG1b; + bn128wasm.pG2gen = moduleBuilder.modules.bn128.pG2gen; + bn128wasm.pG2zero = moduleBuilder.modules.bn128.pG2zero; + bn128wasm.pG2b = moduleBuilder.modules.bn128.pG2b; + bn128wasm.pOneT = moduleBuilder.modules.bn128.pOneT; + bn128wasm.prePSize = moduleBuilder.modules.bn128.prePSize; + bn128wasm.preQSize = moduleBuilder.modules.bn128.preQSize; + bn128wasm.n8q = 32; + bn128wasm.n8r = 32; + bn128wasm.q = moduleBuilder.modules.bn128.q; + bn128wasm.r = moduleBuilder.modules.bn128.r; + + if ((!singleThread) && (globalThis.curve_bn128)) return globalThis.curve_bn128; + const params = { + name: "bn128", + wasm: bn128wasm, + q: e("21888242871839275222246405745257275088696311157297823662689037894645226208583"), + r: e("21888242871839275222246405745257275088548364400416034343698204186575808495617"), + n8q: 32, + n8r: 32, + cofactorG2: e("30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d", 16), + singleThread: singleThread ? true : false + }; + + const curve = await buildEngine(params); + curve.terminate = async function () { + if (!params.singleThread) { + globalThis.curve_bn128 = null; + await this.tm.terminate(); + } + }; + + if (!singleThread) { + globalThis.curve_bn128 = curve; + } + + return curve; +} + +globalThis.curve_bls12381 = null; + +async function buildBls12381(singleThread, plugins) { + + const moduleBuilder = new ModuleBuilder(); + moduleBuilder.setMemory(25); + buildBls12381$1(moduleBuilder); + + if (plugins) plugins(moduleBuilder); + + const bls12381wasm = {}; + + bls12381wasm.code = moduleBuilder.build(); + bls12381wasm.pq = moduleBuilder.modules.f1m.pq; + bls12381wasm.pr = moduleBuilder.modules.frm.pq; + bls12381wasm.pG1gen = moduleBuilder.modules.bls12381.pG1gen; + bls12381wasm.pG1zero = moduleBuilder.modules.bls12381.pG1zero; + bls12381wasm.pG1b = moduleBuilder.modules.bls12381.pG1b; + bls12381wasm.pG2gen = moduleBuilder.modules.bls12381.pG2gen; + bls12381wasm.pG2zero = moduleBuilder.modules.bls12381.pG2zero; + bls12381wasm.pG2b = moduleBuilder.modules.bls12381.pG2b; + bls12381wasm.pOneT = moduleBuilder.modules.bls12381.pOneT; + bls12381wasm.prePSize = moduleBuilder.modules.bls12381.prePSize; + bls12381wasm.preQSize = moduleBuilder.modules.bls12381.preQSize; + bls12381wasm.n8q = 48; + bls12381wasm.n8r = 32; + bls12381wasm.q = moduleBuilder.modules.bn128.q; + bls12381wasm.r = moduleBuilder.modules.bn128.r; + + + if ((!singleThread) && (globalThis.curve_bls12381)) return globalThis.curve_bls12381; + const params = { + name: "bls12381", + wasm: bls12381wasm, + q: e("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16), + r: e("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16), + n8q: 48, + n8r: 32, + cofactorG1: e("0x396c8c005555e1568c00aaab0000aaab", 16), + cofactorG2: e("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5", 16), + singleThread: singleThread ? true : false + }; + + const curve = await buildEngine(params); + curve.terminate = async function () { + if (!params.singleThread) { + globalThis.curve_bls12381 = null; + await this.tm.terminate(); + } + }; + + if (!singleThread) { + globalThis.curve_bls12381 = curve; + } + + return curve; +} + +e("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); +e("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + +e("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); +e("21888242871839275222246405745257275088696311157297823662689037894645226208583"); + +async function getCurveFromName(name, singleThread, plugins) { + let curve; + const normName = normalizeName(name); + if (["BN128", "BN254", "ALTBN128"].indexOf(normName) >= 0) { + curve = await buildBn128(singleThread, plugins); + } else if (["BLS12381"].indexOf(normName) >= 0) { + curve = await buildBls12381(singleThread, plugins); + } else { + throw new Error(`Curve not supported: ${name}`); + } + return curve; + + function normalizeName(n) { + return n.toUpperCase().match(/[A-Za-z0-9]+/g).join(""); + } + +} + +const Scalar=_Scalar; + +const version$2 = "logger/5.7.0"; + +let _permanentCensorErrors = false; +let _censorErrors = false; +const LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 }; +let _logLevel = LogLevels["default"]; +let _globalLogger = null; +function _checkNormalize() { + try { + const missing = []; + // Make sure all forms of normalization are supported + ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => { + try { + if ("test".normalize(form) !== "test") { + throw new Error("bad normalize"); + } + } + catch (error) { + missing.push(form); + } + }); + if (missing.length) { + throw new Error("missing " + missing.join(", ")); + } + if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) { + throw new Error("broken implementation"); + } + } + catch (error) { + return error.message; + } + return null; +} +const _normalizeError = _checkNormalize(); +var LogLevel; +(function (LogLevel) { + LogLevel["DEBUG"] = "DEBUG"; + LogLevel["INFO"] = "INFO"; + LogLevel["WARNING"] = "WARNING"; + LogLevel["ERROR"] = "ERROR"; + LogLevel["OFF"] = "OFF"; +})(LogLevel || (LogLevel = {})); +var ErrorCode; +(function (ErrorCode) { + /////////////////// + // Generic Errors + // Unknown Error + ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; + // Not Implemented + ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; + // Unsupported Operation + // - operation + ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; + // Network Error (i.e. Ethereum Network, such as an invalid chain ID) + // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown) + ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR"; + // Some sort of bad response from the server + ErrorCode["SERVER_ERROR"] = "SERVER_ERROR"; + // Timeout + ErrorCode["TIMEOUT"] = "TIMEOUT"; + /////////////////// + // Operational Errors + // Buffer Overrun + ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; + // Numeric Fault + // - operation: the operation being executed + // - fault: the reason this faulted + ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT"; + /////////////////// + // Argument Errors + // Missing new operator to an object + // - name: The name of the class + ErrorCode["MISSING_NEW"] = "MISSING_NEW"; + // Invalid argument (e.g. value is incompatible with type) to a function: + // - argument: The argument name that was invalid + // - value: The value of the argument + ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; + // Missing argument to a function: + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; + // Too many arguments + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; + /////////////////// + // Blockchain Errors + // Call exception + // - transaction: the transaction + // - address?: the contract address + // - args?: The arguments passed into the function + // - method?: The Solidity method signature + // - errorSignature?: The EIP848 error signature + // - errorArgs?: The EIP848 error parameters + // - reason: The reason (only for EIP848 "Error(string)") + ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION"; + // Insufficient funds (< value + gasLimit * gasPrice) + // - transaction: the transaction attempted + ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; + // Nonce has already been used + // - transaction: the transaction attempted + ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED"; + // The replacement fee for the transaction is too low + // - transaction: the transaction attempted + ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; + // The gas limit could not be estimated + // - transaction: the transaction passed to estimateGas + ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; + // The transaction was replaced by one with a higher gas price + // - reason: "cancelled", "replaced" or "repriced" + // - cancelled: true if reason == "cancelled" or reason == "replaced") + // - hash: original transaction hash + // - replacement: the full TransactionsResponse for the replacement + // - receipt: the receipt of the replacement + ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; + /////////////////// + // Interaction Errors + // The user rejected the action, such as signing a message or sending + // a transaction + ErrorCode["ACTION_REJECTED"] = "ACTION_REJECTED"; +})(ErrorCode || (ErrorCode = {})); +const HEX = "0123456789abcdef"; +class Logger { + constructor(version) { + Object.defineProperty(this, "version", { + enumerable: true, + value: version, + writable: false + }); + } + _log(logLevel, args) { + const level = logLevel.toLowerCase(); + if (LogLevels[level] == null) { + this.throwArgumentError("invalid log level name", "logLevel", logLevel); + } + if (_logLevel > LogLevels[level]) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this._log(Logger.levels.DEBUG, args); + } + info(...args) { + this._log(Logger.levels.INFO, args); + } + warn(...args) { + this._log(Logger.levels.WARNING, args); + } + makeError(message, code, params) { + // Errors are being censored + if (_censorErrors) { + return this.makeError("censored error", code, {}); + } + if (!code) { + code = Logger.errors.UNKNOWN_ERROR; + } + if (!params) { + params = {}; + } + const messageDetails = []; + Object.keys(params).forEach((key) => { + const value = params[key]; + try { + if (value instanceof Uint8Array) { + let hex = ""; + for (let i = 0; i < value.length; i++) { + hex += HEX[value[i] >> 4]; + hex += HEX[value[i] & 0x0f]; + } + messageDetails.push(key + "=Uint8Array(0x" + hex + ")"); + } + else { + messageDetails.push(key + "=" + JSON.stringify(value)); + } + } + catch (error) { + messageDetails.push(key + "=" + JSON.stringify(params[key].toString())); + } + }); + messageDetails.push(`code=${code}`); + messageDetails.push(`version=${this.version}`); + const reason = message; + let url = ""; + switch (code) { + case ErrorCode.NUMERIC_FAULT: { + url = "NUMERIC_FAULT"; + const fault = message; + switch (fault) { + case "overflow": + case "underflow": + case "division-by-zero": + url += "-" + fault; + break; + case "negative-power": + case "negative-width": + url += "-unsupported"; + break; + case "unbound-bitwise-result": + url += "-unbound-result"; + break; + } + break; + } + case ErrorCode.CALL_EXCEPTION: + case ErrorCode.INSUFFICIENT_FUNDS: + case ErrorCode.MISSING_NEW: + case ErrorCode.NONCE_EXPIRED: + case ErrorCode.REPLACEMENT_UNDERPRICED: + case ErrorCode.TRANSACTION_REPLACED: + case ErrorCode.UNPREDICTABLE_GAS_LIMIT: + url = code; + break; + } + if (url) { + message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]"; + } + if (messageDetails.length) { + message += " (" + messageDetails.join(", ") + ")"; + } + // @TODO: Any?? + const error = new Error(message); + error.reason = reason; + error.code = code; + Object.keys(params).forEach(function (key) { + error[key] = params[key]; + }); + return error; + } + throwError(message, code, params) { + throw this.makeError(message, code, params); + } + throwArgumentError(message, name, value) { + return this.throwError(message, Logger.errors.INVALID_ARGUMENT, { + argument: name, + value: value + }); + } + assert(condition, message, code, params) { + if (!!condition) { + return; + } + this.throwError(message, code, params); + } + assertArgument(condition, message, name, value) { + if (!!condition) { + return; + } + this.throwArgumentError(message, name, value); + } + checkNormalize(message) { + if (_normalizeError) { + this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "String.prototype.normalize", form: _normalizeError + }); + } + } + checkSafeUint53(value, message) { + if (typeof (value) !== "number") { + return; + } + if (message == null) { + message = "value not safe"; + } + if (value < 0 || value >= 0x1fffffffffffff) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "out-of-safe-range", + value: value + }); + } + if (value % 1) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "non-integer", + value: value + }); + } + } + checkArgumentCount(count, expectedCount, message) { + if (message) { + message = ": " + message; + } + else { + message = ""; + } + if (count < expectedCount) { + this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + } + checkNew(target, kind) { + if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + checkAbstract(target, kind) { + if (target === kind) { + this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" }); + } + else if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + static globalLogger() { + if (!_globalLogger) { + _globalLogger = new Logger(version$2); + } + return _globalLogger; + } + static setCensorship(censorship, permanent) { + if (!censorship && permanent) { + this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + if (_permanentCensorErrors) { + if (!censorship) { + return; + } + this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + _censorErrors = !!censorship; + _permanentCensorErrors = !!permanent; + } + static setLogLevel(logLevel) { + const level = LogLevels[logLevel.toLowerCase()]; + if (level == null) { + Logger.globalLogger().warn("invalid log level - " + logLevel); + return; + } + _logLevel = level; + } + static from(version) { + return new Logger(version); + } +} +Logger.errors = ErrorCode; +Logger.levels = LogLevel; + +const version$1 = "bytes/5.7.0"; + +const logger$1 = new Logger(version$1); +/////////////////////////////// +function isHexable(value) { + return !!(value.toHexString); +} +function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function () { + const args = Array.prototype.slice.call(arguments); + return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); + }; + return array; +} +function isInteger(value) { + return (typeof (value) === "number" && value == value && (value % 1) === 0); +} +function isBytes(value) { + if (value == null) { + return false; + } + if (value.constructor === Uint8Array) { + return true; + } + if (typeof (value) === "string") { + return false; + } + if (!isInteger(value.length) || value.length < 0) { + return false; + } + for (let i = 0; i < value.length; i++) { + const v = value[i]; + if (!isInteger(v) || v < 0 || v >= 256) { + return false; + } + } + return true; +} +function arrayify(value, options) { + if (!options) { + options = {}; + } + if (typeof (value) === "number") { + logger$1.checkSafeUint53(value, "invalid arrayify value"); + const result = []; + while (value) { + result.unshift(value & 0xff); + value = parseInt(String(value / 256)); + } + if (result.length === 0) { + result.push(0); + } + return addSlice(new Uint8Array(result)); + } + if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + value = value.toHexString(); + } + if (isHexString(value)) { + let hex = value.substring(2); + if (hex.length % 2) { + if (options.hexPad === "left") { + hex = "0" + hex; + } + else if (options.hexPad === "right") { + hex += "0"; + } + else { + logger$1.throwArgumentError("hex data is odd-length", "value", value); + } + } + const result = []; + for (let i = 0; i < hex.length; i += 2) { + result.push(parseInt(hex.substring(i, i + 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + if (isBytes(value)) { + return addSlice(new Uint8Array(value)); + } + return logger$1.throwArgumentError("invalid arrayify value", "value", value); +} +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (length && value.length !== 2 + 2 * length) { + return false; + } + return true; +} + +var sha3$1 = {exports: {}}; + +/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ + +(function (module) { + /*jslint bitwise: true */ + (function () { + + var INPUT_ERROR = 'input is invalid type'; + var FINALIZE_ERROR = 'finalize already called'; + var WINDOW = typeof window === 'object'; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === 'object'; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = commonjsGlobal; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && 'object' === 'object' && module.exports; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var CSHAKE_PADDING = [4, 1024, 262144, 67108864]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest']; + var CSHAKE_BYTEPAD = { + '128': 168, + '256': 136 + }; + + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + } + + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function (obj) { + return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createCshakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits, n, s) { + return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); + }; + }; + + var createKmacOutputMethod = function (bits, padding, outputType) { + return function (key, message, outputBits, s) { + return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); + }; + }; + + var createOutputMethods = function (method, createMethod, bits, padding) { + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createMethod(bits, padding, type); + } + return method; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits, padding); + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits, padding); + }; + + var createCshakeMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createCshakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits, n, s) { + if (!n && !s) { + return methods['shake' + bits].create(outputBits); + } else { + return new Keccak(bits, padding, outputBits).bytepad([n, s], w); + } + }; + method.update = function (message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits, padding); + }; + + var createKmacMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createKmacOutputMethod(bits, padding, 'hex'); + method.create = function (key, outputBits, s) { + return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w); + }; + method.update = function (key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits, padding); + }; + + var algorithms = [ + { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, + { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod }, + { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod }, + { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod }, + { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod } + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name + '_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== 'sha3') { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== 'string') { + if (type === 'object') { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.encode = function (x, right) { + var o = x & 255, n = 1; + var bytes = [o]; + x = x >> 8; + o = x & 255; + while (o > 0) { + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + + Keccak.prototype.encodeString = function (str) { + var notString, type = typeof str; + if (type !== 'string') { + if (type === 'object') { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for (var i = 0; i < str.length; ++i) { + var code = str.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code < 0xd800 || code >= 0xe000) { + bytes += 3; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + + Keccak.prototype.bytepad = function (strs, w) { + var bytes = this.encode(w); + for (var i = 0; i < strs.length; ++i) { + bytes += this.encodeString(strs[i]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + + Keccak.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + function Kmac(bits, padding, outputBits) { + Keccak.call(this, bits, padding, outputBits); + } + + Kmac.prototype = new Keccak(); + + Kmac.prototype.finalize = function () { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + } + })(); +} (sha3$1)); + +var sha3Exports = sha3$1.exports; +var sha3 = /*@__PURE__*/getDefaultExportFromCjs(sha3Exports); + +function keccak256(data) { + return '0x' + sha3.keccak_256(arrayify(data)); +} + +const version = "strings/5.7.0"; + +const logger = new Logger(version); +/////////////////////////////// +var UnicodeNormalizationForm; +(function (UnicodeNormalizationForm) { + UnicodeNormalizationForm["current"] = ""; + UnicodeNormalizationForm["NFC"] = "NFC"; + UnicodeNormalizationForm["NFD"] = "NFD"; + UnicodeNormalizationForm["NFKC"] = "NFKC"; + UnicodeNormalizationForm["NFKD"] = "NFKD"; +})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); +var Utf8ErrorReason; +(function (Utf8ErrorReason) { + // A continuation byte was present where there was nothing to continue + // - offset = the index the codepoint began in + Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; + // An invalid (non-continuation) byte to start a UTF-8 codepoint was found + // - offset = the index the codepoint began in + Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix"; + // The string is too short to process the expected codepoint + // - offset = the index the codepoint began in + Utf8ErrorReason["OVERRUN"] = "string overrun"; + // A missing continuation byte was expected but not found + // - offset = the index the continuation byte was expected at + Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte"; + // The computed code point is outside the range for UTF-8 + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; outside the UTF-8 range + Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range"; + // UTF-8 strings may not contain UTF-16 surrogate pairs + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range + Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate"; + // The string is an overlong representation + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; already bounds checked + Utf8ErrorReason["OVERLONG"] = "overlong representation"; +})(Utf8ErrorReason || (Utf8ErrorReason = {})); +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { + if (form != UnicodeNormalizationForm.current) { + logger.checkNormalize(); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return arrayify(result); +} + +const SEED = "mimcsponge"; +const NROUNDS = 220; + +async function buildMimcSponge() { + const bn128 = await getCurveFromName("bn128", true); + return new MimcSponge(bn128.Fr); +} + +class MimcSponge { + constructor (F) { + this.F = F; + this.cts = this.getConstants(SEED, NROUNDS); + } + + getIV (seed) { + const F = this.F; + if (typeof seed === "undefined") seed = SEED; + const c = keccak256(toUtf8Bytes(seed+"_iv")); + const cn = Scalar.e(c); + const iv = cn.mod(F.p); + return iv; + }; + + getConstants (seed, nRounds) { + const F = this.F; + if (typeof nRounds === "undefined") nRounds = NROUNDS; + const cts = new Array(nRounds); + let c = keccak256(toUtf8Bytes(SEED)); for (let i=1; i { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +class Mimc { + constructor() { + this.mimcPromise = this.initMimc(); + } + initMimc() { + return __async$1(this, null, function* () { + this.sponge = yield buildMimcSponge(); + this.hash = (left, right) => { + var _a, _b; + return (_b = this.sponge) == null ? void 0 : _b.F.toString((_a = this.sponge) == null ? void 0 : _a.multiHash([BigInt(left), BigInt(right)])); + }; + }); + } + getHash() { + return __async$1(this, null, function* () { + yield this.mimcPromise; + return { + sponge: this.sponge, + hash: this.hash + }; + }); + } +} +const mimc = new Mimc(); + +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !process.browser && typeof globalThis.window === "undefined"; + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function nodePostWork() { + return __async(this, null, function* () { + const { hash: hashFunction } = yield mimc.getHash(); + const { merkleTreeHeight, edge, elements, zeroElement } = threads.workerData; + if (edge) { + const merkleTree2 = new lib.PartialMerkleTree(merkleTreeHeight, edge, elements, { + zeroElement, + hashFunction + }); + threads.parentPort.postMessage(merkleTree2.toString()); + return; + } + const merkleTree = new lib.MerkleTree(merkleTreeHeight, elements, { + zeroElement, + hashFunction + }); + threads.parentPort.postMessage(merkleTree.toString()); + }); +} +if (isNode && threads) { + nodePostWork(); +} else if (!isNode && typeof addEventListener === "function" && typeof postMessage === "function") { + addEventListener("message", (e) => __async(undefined, null, function* () { + let data; + if (e.data) { + data = e.data; + } else { + data = e; + } + const { hash: hashFunction } = yield mimc.getHash(); + const { merkleTreeHeight, edge, elements, zeroElement } = data; + if (edge) { + const merkleTree2 = new lib.PartialMerkleTree(merkleTreeHeight, edge, elements, { + zeroElement, + hashFunction + }); + postMessage(merkleTree2.toString()); + return; + } + const merkleTree = new lib.MerkleTree(merkleTreeHeight, elements, { + zeroElement, + hashFunction + }); + postMessage(merkleTree.toString()); + })); +} else { + throw new Error("This browser / environment does not support workers!"); +} diff --git a/dist/merkleTreeWorker.umd.js b/dist/merkleTreeWorker.umd.js new file mode 100644 index 0000000..e29bdd7 --- /dev/null +++ b/dist/merkleTreeWorker.umd.js @@ -0,0 +1,105868 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 7736: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseTree = void 0; +class BaseTree { + get capacity() { + return 2 ** this.levels; + } + get layers() { + return this._layers.slice(); + } + get zeros() { + return this._zeros.slice(); + } + get elements() { + return this._layers[0].slice(); + } + get root() { + var _a; + return (_a = this._layers[this.levels][0]) !== null && _a !== void 0 ? _a : this._zeros[this.levels]; + } + /** + * Find an element in the tree + * @param elements elements of tree + * @param element An element to find + * @param comparator A function that checks leaf value equality + * @param fromIndex The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned + * @returns {number} Index if element is found, otherwise -1 + */ + static indexOf(elements, element, fromIndex, comparator) { + if (comparator) { + return elements.findIndex((el) => comparator(element, el)); + } + else { + return elements.indexOf(element, fromIndex); + } + } + /** + * Insert new element into the tree + * @param element Element to insert + */ + insert(element) { + if (this._layers[0].length >= this.capacity) { + throw new Error('Tree is full'); + } + this.update(this._layers[0].length, element); + } + /* + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = this._layers[level - 1][index * 2 + 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } + this.insert(elements[elements.length - 1]); + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + /** + * Get merkle path to a leaf + * @param {number} index Leaf index to generate path for + * @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index + */ + path(index) { + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + let elIndex = +index; + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + _buildZeros() { + this._zeros = [this.zeroElement]; + for (let i = 1; i <= this.levels; i++) { + this._zeros[i] = this._hashFn(this._zeros[i - 1], this._zeros[i - 1]); + } + } + _processNodes(nodes, layerIndex) { + const length = nodes.length; + let currentLength = Math.ceil(length / 2); + const currentLayer = new Array(currentLength); + currentLength--; + const starFrom = length - ((length % 2) ^ 1); + let j = 0; + for (let i = starFrom; i >= 0; i -= 2) { + if (nodes[i - 1] === undefined) + break; + const left = nodes[i - 1]; + const right = (i === starFrom && length % 2 === 1) ? this._zeros[layerIndex - 1] : nodes[i]; + currentLayer[currentLength - j] = this._hashFn(left, right); + j++; + } + return currentLayer; + } + _processUpdate(index) { + for (let level = 1; level <= this.levels; level++) { + index >>= 1; + const left = this._layers[level - 1][index * 2]; + const right = index * 2 + 1 < this._layers[level - 1].length + ? this._layers[level - 1][index * 2 + 1] + : this._zeros[level - 1]; + this._layers[level][index] = this._hashFn(left, right); + } + } +} +exports.BaseTree = BaseTree; + + +/***/ }), + +/***/ 9093: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class MerkleTree extends BaseTree_1.BaseTree { + constructor(levels, elements = [], { hashFunction = simpleHash_1.default, zeroElement = 0, } = {}) { + super(); + this.levels = levels; + if (elements.length > this.capacity) { + throw new Error('Tree is full'); + } + this._hashFn = hashFunction; + this.zeroElement = zeroElement; + this._layers = []; + const leaves = elements.slice(); + this._layers = [leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + this._layers[layerIndex] = this._processNodes(nodes, layerIndex); + } + } + /** + * Insert multiple elements into the tree. + * @param {Array} elements Elements to insert + */ + bulkInsert(elements) { + if (!elements.length) { + return; + } + if (this._layers[0].length + elements.length > this.capacity) { + throw new Error('Tree is full'); + } + // First we insert all elements except the last one + // updating only full subtree hashes (all layers where inserted element has odd index) + // the last element will update the full path to the root making the tree consistent again + for (let i = 0; i < elements.length - 1; i++) { + this._layers[0].push(elements[i]); + let level = 0; + let index = this._layers[0].length - 1; + while (index % 2 === 1) { + level++; + index >>= 1; + this._layers[level][index] = this._hashFn(this._layers[level - 1][index * 2], this._layers[level - 1][index * 2 + 1]); + } + } + this.insert(elements[elements.length - 1]); + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, 0, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + getTreeEdge(edgeIndex) { + const edgeElement = this._layers[0][edgeIndex]; + if (edgeElement === undefined) { + throw new Error('Element not found'); + } + const edgePath = this.path(edgeIndex); + return { edgePath, edgeElement, edgeIndex, edgeElementsCount: this._layers[0].length }; + } + /** + * 🪓 + * @param count + */ + getTreeSlices(count = 4) { + const length = this._layers[0].length; + let size = Math.ceil(length / count); + if (size % 2) + size++; + const slices = []; + for (let i = 0; i < length; i += size) { + const edgeLeft = i; + const edgeRight = i + size; + slices.push({ edge: this.getTreeEdge(edgeLeft), elements: this.elements.slice(edgeLeft, edgeRight) }); + } + return slices; + } + /** + * Serialize entire tree state including intermediate layers into a plain object + * Deserializing it back will not require to recompute any hashes + * Elements are not converted to a plain type, this is responsibility of the caller + */ + serialize() { + return { + levels: this.levels, + _zeros: this._zeros, + _layers: this._layers, + }; + } + /** + * Deserialize data into a MerkleTree instance + * Make sure to provide the same hashFunction as was used in the source tree, + * otherwise the tree state will be invalid + */ + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance.zeroElement = instance._zeros[0]; + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports["default"] = MerkleTree; + + +/***/ }), + +/***/ 1230: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PartialMerkleTree = void 0; +const simpleHash_1 = __importDefault(__webpack_require__(5319)); +const BaseTree_1 = __webpack_require__(7736); +class PartialMerkleTree extends BaseTree_1.BaseTree { + constructor(levels, { edgePath, edgeElement, edgeIndex, edgeElementsCount, }, leaves, { hashFunction, zeroElement } = {}) { + super(); + if (edgeIndex + leaves.length !== edgeElementsCount) + throw new Error('Invalid number of elements'); + this._edgeLeafProof = edgePath; + this._initialRoot = edgePath.pathRoot; + this.zeroElement = zeroElement !== null && zeroElement !== void 0 ? zeroElement : 0; + this._edgeLeaf = { data: edgeElement, index: edgeIndex }; + this._leavesAfterEdge = leaves; + this.levels = levels; + this._hashFn = hashFunction || simpleHash_1.default; + this._createProofMap(); + this._buildTree(); + } + get edgeIndex() { + return this._edgeLeaf.index; + } + get edgeElement() { + return this._edgeLeaf.data; + } + get edgeLeafProof() { + return this._edgeLeafProof; + } + _createProofMap() { + this._proofMap = this.edgeLeafProof.pathPositions.reduce((p, c, i) => { + p.set(i, [c, this.edgeLeafProof.pathElements[i]]); + return p; + }, new Map()); + this._proofMap.set(this.levels, [0, this.edgeLeafProof.pathRoot]); + } + _buildTree() { + const edgeLeafIndex = this._edgeLeaf.index; + this._leaves = Array(edgeLeafIndex).concat(this._leavesAfterEdge); + if (this._proofMap.has(0)) { + const [proofPos, proofEl] = this._proofMap.get(0); + this._leaves[proofPos] = proofEl; + } + this._layers = [this._leaves]; + this._buildZeros(); + this._buildHashes(); + } + _buildHashes() { + for (let layerIndex = 1; layerIndex <= this.levels; layerIndex++) { + const nodes = this._layers[layerIndex - 1]; + const currentLayer = this._processNodes(nodes, layerIndex); + if (this._proofMap.has(layerIndex)) { + const [proofPos, proofEl] = this._proofMap.get(layerIndex); + if (!currentLayer[proofPos]) + currentLayer[proofPos] = proofEl; + } + this._layers[layerIndex] = currentLayer; + } + } + /** + * Change an element in the tree + * @param {number} index Index of element to change + * @param element Updated element value + */ + update(index, element) { + if (isNaN(Number(index)) || index < 0 || index > this._layers[0].length || index >= this.capacity) { + throw new Error('Insert index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + this._layers[0][index] = element; + this._processUpdate(index); + } + path(index) { + var _a; + if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) { + throw new Error('Index out of bounds: ' + index); + } + if (index < this._edgeLeaf.index) { + throw new Error(`Index ${index} is below the edge: ${this._edgeLeaf.index}`); + } + let elIndex = Number(index); + const pathElements = []; + const pathIndices = []; + const pathPositions = []; + for (let level = 0; level < this.levels; level++) { + pathIndices[level] = elIndex % 2; + const leafIndex = elIndex ^ 1; + if (leafIndex < this._layers[level].length) { + pathElements[level] = this._layers[level][leafIndex]; + pathPositions[level] = leafIndex; + } + else { + pathElements[level] = this._zeros[level]; + pathPositions[level] = 0; + } + const [proofPos, proofEl] = this._proofMap.get(level); + pathElements[level] = (_a = pathElements[level]) !== null && _a !== void 0 ? _a : (proofPos === leafIndex ? proofEl : this._zeros[level]); + elIndex >>= 1; + } + return { + pathElements, + pathIndices, + pathPositions, + pathRoot: this.root, + }; + } + indexOf(element, comparator) { + return BaseTree_1.BaseTree.indexOf(this._layers[0], element, this.edgeIndex, comparator); + } + proof(element) { + const index = this.indexOf(element); + return this.path(index); + } + /** + * Shifts edge of tree to left + * @param edge new TreeEdge below current edge + * @param elements leaves between old and new edge + */ + shiftEdge(edge, elements) { + if (this._edgeLeaf.index <= edge.edgeIndex) { + throw new Error(`New edgeIndex should be smaller then ${this._edgeLeaf.index}`); + } + if (elements.length !== (this._edgeLeaf.index - edge.edgeIndex)) { + throw new Error(`Elements length should be ${this._edgeLeaf.index - edge.edgeIndex}`); + } + this._edgeLeafProof = edge.edgePath; + this._edgeLeaf = { index: edge.edgeIndex, data: edge.edgeElement }; + this._leavesAfterEdge = [...elements, ...this._leavesAfterEdge]; + this._createProofMap(); + this._buildTree(); + } + serialize() { + return { + _edgeLeafProof: this._edgeLeafProof, + _edgeLeaf: this._edgeLeaf, + _layers: this._layers, + _zeros: this._zeros, + levels: this.levels, + }; + } + static deserialize(data, hashFunction) { + const instance = Object.assign(Object.create(this.prototype), data); + instance._hashFn = hashFunction || simpleHash_1.default; + instance._initialRoot = data._edgeLeafProof.pathRoot; + instance.zeroElement = instance._zeros[0]; + instance._leavesAfterEdge = instance._layers[0].slice(data._edgeLeaf.index); + instance._createProofMap(); + return instance; + } + toString() { + return JSON.stringify(this.serialize()); + } +} +exports.PartialMerkleTree = PartialMerkleTree; + + +/***/ }), + +/***/ 1217: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MerkleTree = exports.simpleHash = exports.PartialMerkleTree = void 0; +const FixedMerkleTree_1 = __importDefault(__webpack_require__(9093)); +Object.defineProperty(exports, "MerkleTree", ({ enumerable: true, get: function () { return FixedMerkleTree_1.default; } })); +var PartialMerkleTree_1 = __webpack_require__(1230); +Object.defineProperty(exports, "PartialMerkleTree", ({ enumerable: true, get: function () { return PartialMerkleTree_1.PartialMerkleTree; } })); +var simpleHash_1 = __webpack_require__(5319); +Object.defineProperty(exports, "simpleHash", ({ enumerable: true, get: function () { return simpleHash_1.simpleHash; } })); +exports["default"] = FixedMerkleTree_1.default; + + +/***/ }), + +/***/ 5319: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.simpleHash = void 0; +/*** + * This is insecure hash function, just for example only + * @param data + * @param seed + * @param hashLength + */ +function simpleHash(data, seed, hashLength = 40) { + const str = data.join(''); + let i, l, hval = seed !== null && seed !== void 0 ? seed : 0x811c9dcc5; + for (i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 6) + (hval << 8) + (hval << 24); + } + const hash = (hval >>> 0).toString(16); + return BigInt('0x' + hash.padEnd(hashLength - (hash.length - 1), '0')).toString(10); +} +exports.simpleHash = simpleHash; +exports["default"] = (left, right) => simpleHash([left, right]); + + +/***/ }), + +/***/ 7568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = exports; + +asn1.bignum = __webpack_require__(2344); + +asn1.define = (__webpack_require__(7363).define); +asn1.base = __webpack_require__(9673); +asn1.constants = __webpack_require__(2153); +asn1.decoders = __webpack_require__(2853); +asn1.encoders = __webpack_require__(4669); + + +/***/ }), + +/***/ 7363: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var asn1 = __webpack_require__(7568); +var inherits = __webpack_require__(6698); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = (__webpack_require__(8961).runInThisContext)( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; + + +/***/ }), + +/***/ 7227: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); +var Reporter = (__webpack_require__(9673).Reporter); +var Buffer = (__webpack_require__(8287).Buffer); + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.t = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.d = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + + +/***/ }), + +/***/ 9673: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var base = exports; + +base.Reporter = (__webpack_require__(9220)/* .Reporter */ .a); +base.DecoderBuffer = (__webpack_require__(7227)/* .DecoderBuffer */ .t); +base.EncoderBuffer = (__webpack_require__(7227)/* .EncoderBuffer */ .d); +base.Node = __webpack_require__(993); + + +/***/ }), + +/***/ 993: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Reporter = (__webpack_require__(9673).Reporter); +var EncoderBuffer = (__webpack_require__(9673).EncoderBuffer); +var DecoderBuffer = (__webpack_require__(9673).DecoderBuffer); +var assert = __webpack_require__(3349); + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + var result = state['default']; + var present = true; + + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); + + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; + + +/***/ }), + +/***/ 9220: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.a = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; +}; + + +/***/ }), + +/***/ 4598: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = __webpack_require__(2153); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + + +/***/ }), + +/***/ 2153: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = __webpack_require__(4598); + + +/***/ }), + +/***/ 2010: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); + +var asn1 = __webpack_require__(7568); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + + +/***/ }), + +/***/ 2853: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var decoders = exports; + +decoders.der = __webpack_require__(2010); +decoders.pem = __webpack_require__(8903); + + +/***/ }), + +/***/ 8903: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); +var Buffer = (__webpack_require__(8287).Buffer); + +var DERDecoder = __webpack_require__(2010); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; + + +/***/ }), + +/***/ 82: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); +var Buffer = (__webpack_require__(8287).Buffer); + +var asn1 = __webpack_require__(7568); +var base = asn1.base; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + + +/***/ }), + +/***/ 4669: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var encoders = exports; + +encoders.der = __webpack_require__(82); +encoders.pem = __webpack_require__(735); + + +/***/ }), + +/***/ 735: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698); + +var DEREncoder = __webpack_require__(82); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + + +/***/ }), + +/***/ 2344: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(8982).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 4148: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +/* provided dependency */ var console = __webpack_require__(6763); +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b + +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +var _require = __webpack_require__(9597), + _require$codes = _require.codes, + ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, + ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; +var AssertionError = __webpack_require__(3918); +var _require2 = __webpack_require__(537), + inspect = _require2.inspect; +var _require$types = (__webpack_require__(537).types), + isPromise = _require$types.isPromise, + isRegExp = _require$types.isRegExp; +var objectAssign = __webpack_require__(1514)(); +var objectIs = __webpack_require__(9394)(); +var RegExpPrototypeTest = __webpack_require__(8075)('RegExp.prototype.test'); +var errorCache = new Map(); +var isDeepEqual; +var isDeepStrictEqual; +var parseExpressionAt; +var findNodeAround; +var decoder; +function lazyLoadComparison() { + var comparison = __webpack_require__(2299); + isDeepEqual = comparison.isDeepEqual; + isDeepStrictEqual = comparison.isDeepStrictEqual; +} + +// Escape control characters but not \n and \t to keep the line breaks and +// indentation intact. +// eslint-disable-next-line no-control-regex +var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; +var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"])); +var escapeFn = function escapeFn(str) { + return meta[str.charCodeAt(0)]; +}; +var warned = false; + +// The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; +var NO_EXCEPTION_SENTINEL = {}; + +// All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function innerFail(obj) { + if (obj.message instanceof Error) throw obj.message; + throw new AssertionError(obj); +} +function fail(actual, expected, message, operator, stackStartFn) { + var argsLen = arguments.length; + var internalMessage; + if (argsLen === 0) { + internalMessage = 'Failed'; + } else if (argsLen === 1) { + message = actual; + actual = undefined; + } else { + if (warned === false) { + warned = true; + var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); + warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); + } + if (argsLen === 2) operator = '!='; + } + if (message instanceof Error) throw message; + var errArgs = { + actual: actual, + expected: expected, + operator: operator === undefined ? 'fail' : operator, + stackStartFn: stackStartFn || fail + }; + if (message !== undefined) { + errArgs.message = message; + } + var err = new AssertionError(errArgs); + if (internalMessage) { + err.message = internalMessage; + err.generatedMessage = true; + } + throw err; +} +assert.fail = fail; + +// The AssertionError is defined in internal/error. +assert.AssertionError = AssertionError; +function innerOk(fn, argLen, value, message) { + if (!value) { + var generatedMessage = false; + if (argLen === 0) { + generatedMessage = true; + message = 'No value argument passed to `assert.ok()`'; + } else if (message instanceof Error) { + throw message; + } + var err = new AssertionError({ + actual: value, + expected: true, + message: message, + operator: '==', + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} + +// Pure assertion tests whether a value is truthy, as determined +// by !!value. +function ok() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + innerOk.apply(void 0, [ok, args.length].concat(args)); +} +assert.ok = ok; + +// The equality assertion tests shallow, coercive equality with ==. +/* eslint-disable no-restricted-properties */ +assert.equal = function equal(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual != expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '==', + stackStartFn: equal + }); + } +}; + +// The non-equality assertion tests for whether two objects are not +// equal with !=. +assert.notEqual = function notEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual == expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '!=', + stackStartFn: notEqual + }); + } +}; + +// The equivalence assertion tests a deep equality relation. +assert.deepEqual = function deepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepEqual', + stackStartFn: deepEqual + }); + } +}; + +// The non-equivalence assertion tests for any deep inequality. +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepEqual', + stackStartFn: notDeepEqual + }); + } +}; +/* eslint-enable */ + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepStrictEqual', + stackStartFn: deepStrictEqual + }); + } +}; +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepStrictEqual', + stackStartFn: notDeepStrictEqual + }); + } +} +assert.strictEqual = function strictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (!objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'strictEqual', + stackStartFn: strictEqual + }); + } +}; +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notStrictEqual', + stackStartFn: notStrictEqual + }); + } +}; +var Comparison = /*#__PURE__*/_createClass(function Comparison(obj, keys, actual) { + var _this = this; + _classCallCheck(this, Comparison); + keys.forEach(function (key) { + if (key in obj) { + if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && RegExpPrototypeTest(obj[key], actual[key])) { + _this[key] = actual[key]; + } else { + _this[key] = obj[key]; + } + } + }); +}); +function compareExceptionKey(actual, expected, key, message, keys, fn) { + if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { + if (!message) { + // Create placeholder objects to create a nice output. + var a = new Comparison(actual, keys); + var b = new Comparison(expected, keys, actual); + var err = new AssertionError({ + actual: a, + expected: b, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.actual = actual; + err.expected = expected; + err.operator = fn.name; + throw err; + } + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: fn.name, + stackStartFn: fn + }); + } +} +function expectedException(actual, expected, msg, fn) { + if (typeof expected !== 'function') { + if (isRegExp(expected)) return RegExpPrototypeTest(expected, actual); + // assert.doesNotThrow does not accept objects. + if (arguments.length === 2) { + throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); + } + + // Handle primitives properly. + if (_typeof(actual) !== 'object' || actual === null) { + var err = new AssertionError({ + actual: actual, + expected: expected, + message: msg, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.operator = fn.name; + throw err; + } + var keys = Object.keys(expected); + // Special handle errors to make sure the name and the message are compared + // as well. + if (expected instanceof Error) { + keys.push('name', 'message'); + } else if (keys.length === 0) { + throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + keys.forEach(function (key) { + if (typeof actual[key] === 'string' && isRegExp(expected[key]) && RegExpPrototypeTest(expected[key], actual[key])) { + return; + } + compareExceptionKey(actual, expected, key, msg, keys, fn); + }); + return true; + } + // Guard instanceof against arrow functions as they don't have a prototype. + if (expected.prototype !== undefined && actual instanceof expected) { + return true; + } + if (Error.isPrototypeOf(expected)) { + return false; + } + return expected.call({}, actual) === true; +} +function getActual(fn) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); + } + try { + fn(); + } catch (e) { + return e; + } + return NO_EXCEPTION_SENTINEL; +} +function checkIsPromise(obj) { + // Accept native ES6 promises and promises that are implemented in a similar + // way. Do not accept thenables that use a function as `obj` and that have no + // `catch` handler. + + // TODO: thenables are checked up until they have the correct methods, + // but according to documentation, the `then` method should receive + // the `fulfill` and `reject` arguments as well or it may be never resolved. + + return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; +} +function waitForActual(promiseFn) { + return Promise.resolve().then(function () { + var resultPromise; + if (typeof promiseFn === 'function') { + // Return a rejected promise if `promiseFn` throws synchronously. + resultPromise = promiseFn(); + // Fail in case no promise is returned. + if (!checkIsPromise(resultPromise)) { + throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); + } + } else if (checkIsPromise(promiseFn)) { + resultPromise = promiseFn; + } else { + throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); + } + return Promise.resolve().then(function () { + return resultPromise; + }).then(function () { + return NO_EXCEPTION_SENTINEL; + }).catch(function (e) { + return e; + }); + }); +} +function expectsError(stackStartFn, actual, error, message) { + if (typeof error === 'string') { + if (arguments.length === 4) { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (_typeof(actual) === 'object' && actual !== null) { + if (actual.message === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); + } + } else if (actual === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); + } + message = error; + error = undefined; + } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (actual === NO_EXCEPTION_SENTINEL) { + var details = ''; + if (error && error.name) { + details += " (".concat(error.name, ")"); + } + details += message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; + innerFail({ + actual: undefined, + expected: error, + operator: stackStartFn.name, + message: "Missing expected ".concat(fnType).concat(details), + stackStartFn: stackStartFn + }); + } + if (error && !expectedException(actual, error, message, stackStartFn)) { + throw actual; + } +} +function expectsNoError(stackStartFn, actual, error, message) { + if (actual === NO_EXCEPTION_SENTINEL) return; + if (typeof error === 'string') { + message = error; + error = undefined; + } + if (!error || expectedException(actual, error)) { + var details = message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; + innerFail({ + actual: actual, + expected: error, + operator: stackStartFn.name, + message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), + stackStartFn: stackStartFn + }); + } + throw actual; +} +assert.throws = function throws(promiseFn) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); +}; +assert.rejects = function rejects(promiseFn) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return waitForActual(promiseFn).then(function (result) { + return expectsError.apply(void 0, [rejects, result].concat(args)); + }); +}; +assert.doesNotThrow = function doesNotThrow(fn) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); +}; +assert.doesNotReject = function doesNotReject(fn) { + for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + return waitForActual(fn).then(function (result) { + return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); + }); +}; +assert.ifError = function ifError(err) { + if (err !== null && err !== undefined) { + var message = 'ifError got unwanted exception: '; + if (_typeof(err) === 'object' && typeof err.message === 'string') { + if (err.message.length === 0 && err.constructor) { + message += err.constructor.name; + } else { + message += err.message; + } + } else { + message += inspect(err); + } + var newErr = new AssertionError({ + actual: err, + expected: null, + operator: 'ifError', + message: message, + stackStartFn: ifError + }); + + // Make sure we actually have a stack trace! + var origStack = err.stack; + if (typeof origStack === 'string') { + // This will remove any duplicated frames from the error frames taken + // from within `ifError` and add the original error frames to the newly + // created ones. + var tmp2 = origStack.split('\n'); + tmp2.shift(); + // Filter all frames existing in err.stack. + var tmp1 = newErr.stack.split('\n'); + for (var i = 0; i < tmp2.length; i++) { + // Find the first occurrence of the frame. + var pos = tmp1.indexOf(tmp2[i]); + if (pos !== -1) { + // Only keep new frames. + tmp1 = tmp1.slice(0, pos); + break; + } + } + newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); + } + throw newErr; + } +}; + +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a871df3dfb8ea663ef5e1f8f62701ec51384ecb +function internalMatch(string, regexp, message, fn, fnName) { + if (!isRegExp(regexp)) { + throw new ERR_INVALID_ARG_TYPE('regexp', 'RegExp', regexp); + } + var match = fnName === 'match'; + if (typeof string !== 'string' || RegExpPrototypeTest(regexp, string) !== match) { + if (message instanceof Error) { + throw message; + } + var generatedMessage = !message; + + // 'The input was expected to not match the regular expression ' + + message = message || (typeof string !== 'string' ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof(string), " (").concat(inspect(string), ")") : (match ? 'The input did not match the regular expression ' : 'The input was expected to not match the regular expression ') + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string), "\n")); + var err = new AssertionError({ + actual: string, + expected: regexp, + message: message, + operator: fnName, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +assert.match = function match(string, regexp, message) { + internalMatch(string, regexp, message, match, 'match'); +}; +assert.doesNotMatch = function doesNotMatch(string, regexp, message) { + internalMatch(string, regexp, message, doesNotMatch, 'doesNotMatch'); +}; + +// Expose a strict only variant of assert +function strict() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + innerOk.apply(void 0, [strict, args.length].concat(args)); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +/***/ }), + +/***/ 3918: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Currently in sync with Node.js lib/internal/assert/assertion_error.js +// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c + + + +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var _require = __webpack_require__(537), + inspect = _require.inspect; +var _require2 = __webpack_require__(9597), + ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat +function repeat(str, count) { + count = Math.floor(count); + if (str.length == 0 || count == 0) return ''; + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; +} +var blue = ''; +var green = ''; +var red = ''; +var white = ''; +var kReadableOperator = { + deepStrictEqual: 'Expected values to be strictly deep-equal:', + strictEqual: 'Expected values to be strictly equal:', + strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', + deepEqual: 'Expected values to be loosely deep-equal:', + equal: 'Expected values to be loosely equal:', + notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', + notStrictEqual: 'Expected "actual" to be strictly unequal to:', + notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', + notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', + notEqual: 'Expected "actual" to be loosely unequal to:', + notIdentical: 'Values identical but not reference-equal:' +}; + +// Comparing short primitives should just show === / !== instead of using the +// diff. +var kMaxShortLength = 10; +function copyError(source) { + var keys = Object.keys(source); + var target = Object.create(Object.getPrototypeOf(source)); + keys.forEach(function (key) { + target[key] = source[key]; + }); + Object.defineProperty(target, 'message', { + value: source.message + }); + return target; +} +function inspectValue(val) { + // The util.inspect default values could be changed. This makes sure the + // error messages contain the necessary information nevertheless. + return inspect(val, { + compact: false, + customInspect: false, + depth: 1000, + maxArrayLength: Infinity, + // Assert compares only enumerable properties (with a few exceptions). + showHidden: false, + // Having a long line as error is better than wrapping the line for + // comparison for now. + // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we + // have meta information about the inspected properties (i.e., know where + // in what line the property starts and ends). + breakLength: Infinity, + // Assert does not detect proxies currently. + showProxy: false, + sorted: true, + // Inspect getters as we also check them when comparing entries. + getters: true + }); +} +function createErrDiff(actual, expected, operator) { + var other = ''; + var res = ''; + var lastPos = 0; + var end = ''; + var skipped = false; + var actualInspected = inspectValue(actual); + var actualLines = actualInspected.split('\n'); + var expectedLines = inspectValue(expected).split('\n'); + var i = 0; + var indicator = ''; + + // In case both values are objects explicitly mark them as not reference equal + // for the `strictEqual` operator. + if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { + operator = 'strictEqualObject'; + } + + // If "actual" and "expected" fit on a single line and they are not strictly + // equal, check further special handling. + if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { + var inputLength = actualLines[0].length + expectedLines[0].length; + // If the character length of "actual" and "expected" together is less than + // kMaxShortLength and if neither is an object and at least one of them is + // not `zero`, use the strict equal comparison to visualize the output. + if (inputLength <= kMaxShortLength) { + if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { + // -0 === +0 + return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); + } + } else if (operator !== 'strictEqualObject') { + // If the stderr is a tty and the input length is lower than the current + // columns per line, add a mismatch indicator below the output. If it is + // not a tty, use a default value of 80 characters. + var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; + if (inputLength < maxLength) { + while (actualLines[0][i] === expectedLines[0][i]) { + i++; + } + // Ignore the first characters. + if (i > 2) { + // Add position indicator for the first mismatch in case it is a + // single line and the input length is less than the column length. + indicator = "\n ".concat(repeat(' ', i), "^"); + i = 0; + } + } + } + } + + // Remove all ending lines that match (this optimizes the output for + // readability by reducing the number of total changed lines). + var a = actualLines[actualLines.length - 1]; + var b = expectedLines[expectedLines.length - 1]; + while (a === b) { + if (i++ < 2) { + end = "\n ".concat(a).concat(end); + } else { + other = a; + } + actualLines.pop(); + expectedLines.pop(); + if (actualLines.length === 0 || expectedLines.length === 0) break; + a = actualLines[actualLines.length - 1]; + b = expectedLines[expectedLines.length - 1]; + } + var maxLines = Math.max(actualLines.length, expectedLines.length); + // Strict equal with identical objects that are not identical by reference. + // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) + if (maxLines === 0) { + // We have to get the result again. The lines were all removed before. + var _actualLines = actualInspected.split('\n'); + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (_actualLines.length > 30) { + _actualLines[26] = "".concat(blue, "...").concat(white); + while (_actualLines.length > 27) { + _actualLines.pop(); + } + } + return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); + } + if (i > 3) { + end = "\n".concat(blue, "...").concat(white).concat(end); + skipped = true; + } + if (other !== '') { + end = "\n ".concat(other).concat(end); + other = ''; + } + var printedLines = 0; + var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); + var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); + for (i = 0; i < maxLines; i++) { + // Only extra expected lines exist + var cur = i - lastPos; + if (actualLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(expectedLines[i - 2]); + printedLines++; + } + res += "\n ".concat(expectedLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the expected line to the cache. + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); + printedLines++; + // Only extra actual lines exist + } else if (expectedLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); + printedLines++; + // Lines diverge + } else { + var expectedLine = expectedLines[i]; + var actualLine = actualLines[i]; + // If the lines diverge, specifically check for lines that only diverge by + // a trailing comma. In that case it is actually identical and we should + // mark it as such. + var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); + // If the expected line has a trailing comma but is otherwise identical, + // add a comma at the end of the actual line. Otherwise the output could + // look weird as in: + // + // [ + // 1 // No comma at the end! + // + 2 + // ] + // + if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { + divergingLines = false; + actualLine += ','; + } + if (divergingLines) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result and cache the expected diverging + // line so consecutive diverging lines show up as +++--- and not +-+-+-. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); + printedLines += 2; + // Lines are identical + } else { + // Add all cached information to the result before adding other things + // and reset the cache. + res += other; + other = ''; + // If the last diverging line is exactly one line above or if it is the + // very first line, add the line to the result. + if (cur === 1 || i === 0) { + res += "\n ".concat(actualLine); + printedLines++; + } + } + } + // Inspected object to big (Show ~20 rows max) + if (printedLines > 20 && i < maxLines - 2) { + return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); + } + } + return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); +} +var AssertionError = /*#__PURE__*/function (_Error, _inspect$custom) { + _inherits(AssertionError, _Error); + var _super = _createSuper(AssertionError); + function AssertionError(options) { + var _this; + _classCallCheck(this, AssertionError); + if (_typeof(options) !== 'object' || options === null) { + throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); + } + var message = options.message, + operator = options.operator, + stackStartFn = options.stackStartFn; + var actual = options.actual, + expected = options.expected; + var limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + if (message != null) { + _this = _super.call(this, String(message)); + } else { + if (process.stderr && process.stderr.isTTY) { + // Reset on each call to make sure we handle dynamically set environment + // variables correct. + if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { + blue = "\x1B[34m"; + green = "\x1B[32m"; + white = "\x1B[39m"; + red = "\x1B[31m"; + } else { + blue = ''; + green = ''; + white = ''; + red = ''; + } + } + // Prevent the error stack from being visible by duplicating the error + // in a very close way to the original in case both sides are actually + // instances of Error. + if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { + actual = copyError(actual); + expected = copyError(expected); + } + if (operator === 'deepStrictEqual' || operator === 'strictEqual') { + _this = _super.call(this, createErrDiff(actual, expected, operator)); + } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { + // In case the objects are equal but the operator requires unequal, show + // the first object and say A equals B + var base = kReadableOperator[operator]; + var res = inspectValue(actual).split('\n'); + + // In case "actual" is an object, it should not be reference equal. + if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { + base = kReadableOperator.notStrictEqualObject; + } + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (res.length > 30) { + res[26] = "".concat(blue, "...").concat(white); + while (res.length > 27) { + res.pop(); + } + } + + // Only print a single input. + if (res.length === 1) { + _this = _super.call(this, "".concat(base, " ").concat(res[0])); + } else { + _this = _super.call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")); + } + } else { + var _res = inspectValue(actual); + var other = ''; + var knownOperators = kReadableOperator[operator]; + if (operator === 'notDeepEqual' || operator === 'notEqual') { + _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); + if (_res.length > 1024) { + _res = "".concat(_res.slice(0, 1021), "..."); + } + } else { + other = "".concat(inspectValue(expected)); + if (_res.length > 512) { + _res = "".concat(_res.slice(0, 509), "..."); + } + if (other.length > 512) { + other = "".concat(other.slice(0, 509), "..."); + } + if (operator === 'deepEqual' || operator === 'equal') { + _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); + } else { + other = " ".concat(operator, " ").concat(other); + } + } + _this = _super.call(this, "".concat(_res).concat(other)); + } + } + Error.stackTraceLimit = limit; + _this.generatedMessage = !message; + Object.defineProperty(_assertThisInitialized(_this), 'name', { + value: 'AssertionError [ERR_ASSERTION]', + enumerable: false, + writable: true, + configurable: true + }); + _this.code = 'ERR_ASSERTION'; + _this.actual = actual; + _this.expected = expected; + _this.operator = operator; + if (Error.captureStackTrace) { + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); + } + // Create error message including the error code in the name. + _this.stack; + // Reset the name. + _this.name = 'AssertionError'; + return _possibleConstructorReturn(_this); + } + _createClass(AssertionError, [{ + key: "toString", + value: function toString() { + return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); + } + }, { + key: _inspect$custom, + value: function value(recurseTimes, ctx) { + // This limits the `actual` and `expected` property default inspection to + // the minimum depth. Otherwise those values would be too verbose compared + // to the actual error message which contains a combined view of these two + // input values. + return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, { + customInspect: false, + depth: 0 + })); + } + }]); + return AssertionError; +}( /*#__PURE__*/_wrapNativeSuper(Error), inspect.custom); +module.exports = AssertionError; + +/***/ }), + +/***/ 9597: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/errors.js +// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f + +/* eslint node-core/documented-errors: "error" */ +/* eslint node-core/alphabetize-errors: "error" */ +/* eslint node-core/prefer-util-format-errors: "error" */ + + + +// The whole point behind this internal module is to allow Node.js to no +// longer be forced to treat every error message change as a semver-major +// change. The NodeError classes here all expose a `code` property whose +// value statically and permanently identifies the error. While the error +// message may change, the code should not. +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var codes = {}; + +// Lazy loaded +var assert; +var util; +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /*#__PURE__*/function (_Base) { + _inherits(NodeError, _Base); + var _super = _createSuper(NodeError); + function NodeError(arg1, arg2, arg3) { + var _this; + _classCallCheck(this, NodeError); + _this = _super.call(this, getMessage(arg1, arg2, arg3)); + _this.code = code; + return _this; + } + return _createClass(NodeError); + }(Base); + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} +createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + if (assert === undefined) assert = __webpack_require__(4148); + assert(typeof name === 'string', "'name' must be a string"); + + // determiner: 'must be' or 'must not be' + var determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + var msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + // TODO(BridgeAR): Improve the output by showing `null` and similar. + msg += ". Received type ".concat(_typeof(actual)); + return msg; +}, TypeError); +createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { + var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; + if (util === undefined) util = __webpack_require__(537); + var inspected = util.inspect(value); + if (inspected.length > 128) { + inspected = "".concat(inspected.slice(0, 128), "..."); + } + return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); +}, TypeError, RangeError); +createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { + var type; + if (value && value.constructor && value.constructor.name) { + type = "instance of ".concat(value.constructor.name); + } else { + type = "type ".concat(_typeof(value)); + } + return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); +}, TypeError); +createErrorType('ERR_MISSING_ARGS', function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (assert === undefined) assert = __webpack_require__(4148); + assert(args.length > 0, 'At least one arg needs to be specified'); + var msg = 'The '; + var len = args.length; + args = args.map(function (a) { + return "\"".concat(a, "\""); + }); + switch (len) { + case 1: + msg += "".concat(args[0], " argument"); + break; + case 2: + msg += "".concat(args[0], " and ").concat(args[1], " arguments"); + break; + default: + msg += args.slice(0, len - 1).join(', '); + msg += ", and ".concat(args[len - 1], " arguments"); + break; + } + return "".concat(msg, " must be specified"); +}, TypeError); +module.exports.codes = codes; + +/***/ }), + +/***/ 2299: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/comparisons.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var regexFlagsSupported = /a/g.flags !== undefined; +var arrayFromSet = function arrayFromSet(set) { + var array = []; + set.forEach(function (value) { + return array.push(value); + }); + return array; +}; +var arrayFromMap = function arrayFromMap(map) { + var array = []; + map.forEach(function (value, key) { + return array.push([key, value]); + }); + return array; +}; +var objectIs = Object.is ? Object.is : __webpack_require__(7653); +var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { + return []; +}; +var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(4133); +function uncurryThis(f) { + return f.call.bind(f); +} +var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); +var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); +var objectToString = uncurryThis(Object.prototype.toString); +var _require$types = (__webpack_require__(537).types), + isAnyArrayBuffer = _require$types.isAnyArrayBuffer, + isArrayBufferView = _require$types.isArrayBufferView, + isDate = _require$types.isDate, + isMap = _require$types.isMap, + isRegExp = _require$types.isRegExp, + isSet = _require$types.isSet, + isNativeError = _require$types.isNativeError, + isBoxedPrimitive = _require$types.isBoxedPrimitive, + isNumberObject = _require$types.isNumberObject, + isStringObject = _require$types.isStringObject, + isBooleanObject = _require$types.isBooleanObject, + isBigIntObject = _require$types.isBigIntObject, + isSymbolObject = _require$types.isSymbolObject, + isFloat32Array = _require$types.isFloat32Array, + isFloat64Array = _require$types.isFloat64Array; +function isNonIndex(key) { + if (key.length === 0 || key.length > 10) return true; + for (var i = 0; i < key.length; i++) { + var code = key.charCodeAt(i); + if (code < 48 || code > 57) return true; + } + // The maximum size for an array is 2 ** 32 -1. + return key.length === 10 && key >= Math.pow(2, 32); +} +function getOwnNonIndexProperties(value) { + return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); +} + +// Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + var x = a.length; + var y = b.length; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +var ONLY_ENUMERABLE = undefined; +var kStrict = true; +var kLoose = false; +var kNoIterator = 0; +var kIsArray = 1; +var kIsSet = 2; +var kIsMap = 3; + +// Check if they have the same source and flags +function areSimilarRegExps(a, b) { + return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); +} +function areSimilarFloatArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (var offset = 0; offset < a.byteLength; offset++) { + if (a[offset] !== b[offset]) { + return false; + } + } + return true; +} +function areSimilarTypedArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; +} +function areEqualArrayBuffers(buf1, buf2) { + return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; +} +function isEqualBoxedPrimitive(val1, val2) { + if (isNumberObject(val1)) { + return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); + } + if (isStringObject(val1)) { + return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); + } + if (isBooleanObject(val1)) { + return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); + } + if (isBigIntObject(val1)) { + return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); + } + return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); +} + +// Notes: Type tags are historical [[Class]] properties that can be set by +// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS +// and retrieved using Object.prototype.toString.call(obj) in JS +// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring +// for a list of tags pre-defined in the spec. +// There are some unspecified tags in the wild too (e.g. typed array tags). +// Since tags can be altered, they only serve fast failures +// +// Typed arrays and buffers are checked by comparing the content in their +// underlying ArrayBuffer. This optimization requires that it's +// reasonable to interpret their underlying memory in the same way, +// which is checked by comparing their type tags. +// (e.g. a Uint8Array and a Uint16Array with the same memory content +// could still be different because they will be interpreted differently). +// +// For strict comparison, objects should have +// a) The same built-in type tags +// b) The same prototypes. + +function innerDeepEqual(val1, val2, strict, memos) { + // All identical values are equivalent, as determined by ===. + if (val1 === val2) { + if (val1 !== 0) return true; + return strict ? objectIs(val1, val2) : true; + } + + // Check more closely if val1 and val2 are equal. + if (strict) { + if (_typeof(val1) !== 'object') { + return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); + } + if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { + return false; + } + if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { + return false; + } + } else { + if (val1 === null || _typeof(val1) !== 'object') { + if (val2 === null || _typeof(val2) !== 'object') { + // eslint-disable-next-line eqeqeq + return val1 == val2; + } + return false; + } + if (val2 === null || _typeof(val2) !== 'object') { + return false; + } + } + var val1Tag = objectToString(val1); + var val2Tag = objectToString(val2); + if (val1Tag !== val2Tag) { + return false; + } + if (Array.isArray(val1)) { + // Check for sparse arrays and general fast path + if (val1.length !== val2.length) { + return false; + } + var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (keys1.length !== keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsArray, keys1); + } + // [browserify] This triggers on certain types in IE (Map/Set) so we don't + // wan't to early return out of the rest of the checks. However we can check + // if the second value is one of these values and the first isn't. + if (val1Tag === '[object Object]') { + // return keyCheck(val1, val2, strict, memos, kNoIterator); + if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { + return false; + } + } + if (isDate(val1)) { + if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { + return false; + } + } else if (isRegExp(val1)) { + if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { + return false; + } + } else if (isNativeError(val1) || val1 instanceof Error) { + // Do not compare the stack as it might differ even though the error itself + // is otherwise identical. + if (val1.message !== val2.message || val1.name !== val2.name) { + return false; + } + } else if (isArrayBufferView(val1)) { + if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { + if (!areSimilarFloatArrays(val1, val2)) { + return false; + } + } else if (!areSimilarTypedArrays(val1, val2)) { + return false; + } + // Buffer.compare returns true, so val1.length === val2.length. If they both + // only contain numeric keys, we don't need to exam further than checking + // the symbols. + var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (_keys.length !== _keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); + } else if (isSet(val1)) { + if (!isSet(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsSet); + } else if (isMap(val1)) { + if (!isMap(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsMap); + } else if (isAnyArrayBuffer(val1)) { + if (!areEqualArrayBuffers(val1, val2)) { + return false; + } + } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator); +} +function getEnumerables(val, keys) { + return keys.filter(function (k) { + return propertyIsEnumerable(val, k); + }); +} +function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { + // For all remaining Object pairs, including Array, objects and Maps, + // equivalence is determined by having: + // a) The same number of owned enumerable properties + // b) The same set of keys/indexes (although not necessarily the same order) + // c) Equivalent values for every corresponding key/index + // d) For Sets and Maps, equal contents + // Note: this accounts for both named and indexed properties on Arrays. + if (arguments.length === 5) { + aKeys = Object.keys(val1); + var bKeys = Object.keys(val2); + + // The pair must have the same number of owned properties. + if (aKeys.length !== bKeys.length) { + return false; + } + } + + // Cheap key test + var i = 0; + for (; i < aKeys.length; i++) { + if (!hasOwnProperty(val2, aKeys[i])) { + return false; + } + } + if (strict && arguments.length === 5) { + var symbolKeysA = objectGetOwnPropertySymbols(val1); + if (symbolKeysA.length !== 0) { + var count = 0; + for (i = 0; i < symbolKeysA.length; i++) { + var key = symbolKeysA[i]; + if (propertyIsEnumerable(val1, key)) { + if (!propertyIsEnumerable(val2, key)) { + return false; + } + aKeys.push(key); + count++; + } else if (propertyIsEnumerable(val2, key)) { + return false; + } + } + var symbolKeysB = objectGetOwnPropertySymbols(val2); + if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { + return false; + } + } else { + var _symbolKeysB = objectGetOwnPropertySymbols(val2); + if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { + return false; + } + } + } + if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { + return true; + } + + // Use memos to handle cycles. + if (memos === undefined) { + memos = { + val1: new Map(), + val2: new Map(), + position: 0 + }; + } else { + // We prevent up to two map.has(x) calls by directly retrieving the value + // and checking for undefined. The map can only contain numbers, so it is + // safe to check for undefined only. + var val2MemoA = memos.val1.get(val1); + if (val2MemoA !== undefined) { + var val2MemoB = memos.val2.get(val2); + if (val2MemoB !== undefined) { + return val2MemoA === val2MemoB; + } + } + memos.position++; + } + memos.val1.set(val1, memos.position); + memos.val2.set(val2, memos.position); + var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); + memos.val1.delete(val1); + memos.val2.delete(val2); + return areEq; +} +function setHasEqualElement(set, val1, strict, memo) { + // Go looking. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var val2 = setValues[i]; + if (innerDeepEqual(val1, val2, strict, memo)) { + // Remove the matching element to make sure we do not check that again. + set.delete(val2); + return true; + } + } + return false; +} + +// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using +// Sadly it is not possible to detect corresponding values properly in case the +// type is a string, number, bigint or boolean. The reason is that those values +// can match lots of different string values (e.g., 1n == '+00001'). +function findLooseMatchingPrimitives(prim) { + switch (_typeof(prim)) { + case 'undefined': + return null; + case 'object': + // Only pass in null as object! + return undefined; + case 'symbol': + return false; + case 'string': + prim = +prim; + // Loose equal entries exist only if the string is possible to convert to + // a regular number and not NaN. + // Fall through + case 'number': + if (numberIsNaN(prim)) { + return false; + } + } + return true; +} +function setMightHaveLoosePrim(a, b, prim) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) return altValue; + return b.has(altValue) && !a.has(altValue); +} +function mapMightHaveLoosePrim(a, b, prim, item, memo) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + var curB = b.get(altValue); + if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { + return false; + } + return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); +} +function setEquiv(a, b, strict, memo) { + // This is a lazily initiated Set of entries which have to be compared + // pairwise. + var set = null; + var aValues = arrayFromSet(a); + for (var i = 0; i < aValues.length; i++) { + var val = aValues[i]; + // Note: Checking for the objects first improves the performance for object + // heavy sets but it is a minor slow down for primitives. As they are fast + // to check this improves the worst case scenario instead. + if (_typeof(val) === 'object' && val !== null) { + if (set === null) { + set = new Set(); + } + // If the specified value doesn't exist in the second set its an not null + // object (or non strict only: a not matching primitive) we'll need to go + // hunting for something thats deep-(strict-)equal to it. To make this + // O(n log n) complexity we have to copy these values in a new set first. + set.add(val); + } else if (!b.has(val)) { + if (strict) return false; + + // Fast path to detect missing string, symbol, undefined and null values. + if (!setMightHaveLoosePrim(a, b, val)) { + return false; + } + if (set === null) { + set = new Set(); + } + set.add(val); + } + } + if (set !== null) { + var bValues = arrayFromSet(b); + for (var _i = 0; _i < bValues.length; _i++) { + var _val = bValues[_i]; + // We have to check if a primitive value is already + // matching and only if it's not, go hunting for it. + if (_typeof(_val) === 'object' && _val !== null) { + if (!setHasEqualElement(set, _val, strict, memo)) return false; + } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function mapHasEqualEntry(set, map, key1, item1, strict, memo) { + // To be able to handle cases like: + // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) + // ... we need to consider *all* matching keys, not just the first we find. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var key2 = setValues[i]; + if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { + set.delete(key2); + return true; + } + } + return false; +} +function mapEquiv(a, b, strict, memo) { + var set = null; + var aEntries = arrayFromMap(a); + for (var i = 0; i < aEntries.length; i++) { + var _aEntries$i = _slicedToArray(aEntries[i], 2), + key = _aEntries$i[0], + item1 = _aEntries$i[1]; + if (_typeof(key) === 'object' && key !== null) { + if (set === null) { + set = new Set(); + } + set.add(key); + } else { + // By directly retrieving the value we prevent another b.has(key) check in + // almost all possible cases. + var item2 = b.get(key); + if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { + if (strict) return false; + // Fast path to detect missing string, symbol, undefined and null + // keys. + if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; + if (set === null) { + set = new Set(); + } + set.add(key); + } + } + } + if (set !== null) { + var bEntries = arrayFromMap(b); + for (var _i2 = 0; _i2 < bEntries.length; _i2++) { + var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), + _key = _bEntries$_i[0], + item = _bEntries$_i[1]; + if (_typeof(_key) === 'object' && _key !== null) { + if (!mapHasEqualEntry(set, a, _key, item, strict, memo)) return false; + } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set, a, _key, item, false, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function objEquiv(a, b, strict, keys, memos, iterationType) { + // Sets and maps don't have their entries accessible via normal object + // properties. + var i = 0; + if (iterationType === kIsSet) { + if (!setEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsMap) { + if (!mapEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsArray) { + for (; i < a.length; i++) { + if (hasOwnProperty(a, i)) { + if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { + return false; + } + } else if (hasOwnProperty(b, i)) { + return false; + } else { + // Array is sparse. + var keysA = Object.keys(a); + for (; i < keysA.length; i++) { + var key = keysA[i]; + if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { + return false; + } + } + if (keysA.length !== Object.keys(b).length) { + return false; + } + return true; + } + } + } + + // The pair must have equivalent values for every corresponding key. + // Possibly expensive deep test: + for (i = 0; i < keys.length; i++) { + var _key2 = keys[i]; + if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) { + return false; + } + } + return true; +} +function isDeepEqual(val1, val2) { + return innerDeepEqual(val1, val2, kLoose); +} +function isDeepStrictEqual(val1, val2) { + return innerDeepEqual(val1, val2, kStrict); +} +module.exports = { + isDeepEqual: isDeepEqual, + isDeepStrictEqual: isDeepStrictEqual +}; + +/***/ }), + +/***/ 5682: +/***/ ((module, exports, __webpack_require__) => { + +const ascii = __webpack_require__(6209) +const base64 = __webpack_require__(943) +const hex = __webpack_require__(1847) +const utf8 = __webpack_require__(6679) +const utf16le = __webpack_require__(5435) + +const LE = new Uint8Array(Uint16Array.of(0xff).buffer)[0] === 0xff + +function codecFor (encoding) { + switch (encoding) { + case 'ascii': + return ascii + case 'base64': + return base64 + case 'hex': + return hex + case 'utf8': + case 'utf-8': + case undefined: + return utf8 + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16le + default: + throw new Error(`Unknown encoding: ${encoding}`) + } +} + +function isBuffer (value) { + return value instanceof Uint8Array +} + +function isEncoding (encoding) { + try { + codecFor(encoding) + return true + } catch { + return false + } +} + +function alloc (size, fill, encoding) { + const buffer = new Uint8Array(size) + if (fill !== undefined) exports.fill(buffer, fill, 0, buffer.byteLength, encoding) + return buffer +} + +function allocUnsafe (size) { + return new Uint8Array(size) +} + +function allocUnsafeSlow (size) { + return new Uint8Array(size) +} + +function byteLength (string, encoding) { + return codecFor(encoding).byteLength(string) +} + +function compare (a, b) { + if (a === b) return 0 + + const len = Math.min(a.byteLength, b.byteLength) + + a = new DataView(a.buffer, a.byteOffset, a.byteLength) + b = new DataView(b.buffer, b.byteOffset, b.byteLength) + + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + const x = a.getUint32(i, LE) + const y = b.getUint32(i, LE) + if (x !== y) break + } + + for (; i < len; i++) { + const x = a.getUint8(i) + const y = b.getUint8(i) + if (x < y) return -1 + if (x > y) return 1 + } + + return a.byteLength > b.byteLength ? 1 : a.byteLength < b.byteLength ? -1 : 0 +} + +function concat (buffers, totalLength) { + if (totalLength === undefined) { + totalLength = buffers.reduce((len, buffer) => len + buffer.byteLength, 0) + } + + const result = new Uint8Array(totalLength) + + let offset = 0 + for (const buffer of buffers) { + if (offset + buffer.byteLength > result.byteLength) { + const sub = buffer.subarray(0, result.byteLength - offset) + result.set(sub, offset) + return result + } + result.set(buffer, offset) + offset += buffer.byteLength + } + + return result +} + +function copy (source, target, targetStart = 0, start = 0, end = source.byteLength) { + if (end > 0 && end < start) return 0 + if (end === start) return 0 + if (source.byteLength === 0 || target.byteLength === 0) return 0 + + if (targetStart < 0) throw new RangeError('targetStart is out of range') + if (start < 0 || start >= source.byteLength) throw new RangeError('sourceStart is out of range') + if (end < 0) throw new RangeError('sourceEnd is out of range') + + if (targetStart >= target.byteLength) targetStart = target.byteLength + if (end > source.byteLength) end = source.byteLength + if (target.byteLength - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (source === target) { + target.copyWithin(targetStart, start, end) + } else { + target.set(source.subarray(start, end), targetStart) + } + + return len +} + +function equals (a, b) { + if (a === b) return true + if (a.byteLength !== b.byteLength) return false + + const len = a.byteLength + + a = new DataView(a.buffer, a.byteOffset, a.byteLength) + b = new DataView(b.buffer, b.byteOffset, b.byteLength) + + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + if (a.getUint32(i, LE) !== b.getUint32(i, LE)) return false + } + + for (; i < len; i++) { + if (a.getUint8(i) !== b.getUint8(i)) return false + } + + return true +} + +function fill (buffer, value, offset, end, encoding) { + if (typeof value === 'string') { + // fill(buffer, string, encoding) + if (typeof offset === 'string') { + encoding = offset + offset = 0 + end = buffer.byteLength + + // fill(buffer, string, offset, encoding) + } else if (typeof end === 'string') { + encoding = end + end = buffer.byteLength + } + } else if (typeof value === 'number') { + value = value & 0xff + } else if (typeof value === 'boolean') { + value = +value + } + + if (offset < 0 || buffer.byteLength < offset || buffer.byteLength < end) { + throw new RangeError('Out of range index') + } + + if (offset === undefined) offset = 0 + if (end === undefined) end = buffer.byteLength + + if (end <= offset) return buffer + + if (!value) value = 0 + + if (typeof value === 'number') { + for (let i = offset; i < end; ++i) { + buffer[i] = value + } + } else { + value = isBuffer(value) ? value : from(value, encoding) + + const len = value.byteLength + + for (let i = 0; i < end - offset; ++i) { + buffer[i + offset] = value[i % len] + } + } + + return buffer +} + +function from (value, encodingOrOffset, length) { + // from(string, encoding) + if (typeof value === 'string') return fromString(value, encodingOrOffset) + + // from(array) + if (Array.isArray(value)) return fromArray(value) + + // from(buffer) + if (ArrayBuffer.isView(value)) return fromBuffer(value) + + // from(arrayBuffer[, byteOffset[, length]]) + return fromArrayBuffer(value, encodingOrOffset, length) +} + +function fromString (string, encoding) { + const codec = codecFor(encoding) + const buffer = new Uint8Array(codec.byteLength(string)) + codec.write(buffer, string, 0, buffer.byteLength) + return buffer +} + +function fromArray (array) { + const buffer = new Uint8Array(array.length) + buffer.set(array) + return buffer +} + +function fromBuffer (buffer) { + const copy = new Uint8Array(buffer.byteLength) + copy.set(buffer) + return copy +} + +function fromArrayBuffer (arrayBuffer, byteOffset, length) { + return new Uint8Array(arrayBuffer, byteOffset, length) +} + +function includes (buffer, value, byteOffset, encoding) { + return indexOf(buffer, value, byteOffset, encoding) !== -1 +} + +function bidirectionalIndexOf (buffer, value, byteOffset, encoding, first) { + if (buffer.byteLength === 0) return -1 + + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset === undefined) { + byteOffset = first ? 0 : (buffer.length - 1) + } else if (byteOffset < 0) { + byteOffset += buffer.byteLength + } + + if (byteOffset >= buffer.byteLength) { + if (first) return -1 + else byteOffset = buffer.byteLength - 1 + } else if (byteOffset < 0) { + if (first) byteOffset = 0 + else return -1 + } + + if (typeof value === 'string') { + value = from(value, encoding) + } else if (typeof value === 'number') { + value = value & 0xff + + if (first) { + return buffer.indexOf(value, byteOffset) + } else { + return buffer.lastIndexOf(value, byteOffset) + } + } + + if (value.byteLength === 0) return -1 + + if (first) { + let foundIndex = -1 + + for (let i = byteOffset; i < buffer.byteLength; i++) { + if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === value.byteLength) return foundIndex + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + value.byteLength > buffer.byteLength) { + byteOffset = buffer.byteLength - value.byteLength + } + + for (let i = byteOffset; i >= 0; i--) { + let found = true + + for (let j = 0; j < value.byteLength; j++) { + if (buffer[i + j] !== value[j]) { + found = false + break + } + } + + if (found) return i + } + } + + return -1 +} + +function indexOf (buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, true /* first */) +} + +function lastIndexOf (buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, false /* last */) +} + +function swap (buffer, n, m) { + const i = buffer[n] + buffer[n] = buffer[m] + buffer[m] = i +} + +function swap16 (buffer) { + const len = buffer.byteLength + + if (len % 2 !== 0) throw new RangeError('Buffer size must be a multiple of 16-bits') + + for (let i = 0; i < len; i += 2) swap(buffer, i, i + 1) + + return buffer +} + +function swap32 (buffer) { + const len = buffer.byteLength + + if (len % 4 !== 0) throw new RangeError('Buffer size must be a multiple of 32-bits') + + for (let i = 0; i < len; i += 4) { + swap(buffer, i, i + 3) + swap(buffer, i + 1, i + 2) + } + + return buffer +} + +function swap64 (buffer) { + const len = buffer.byteLength + + if (len % 8 !== 0) throw new RangeError('Buffer size must be a multiple of 64-bits') + + for (let i = 0; i < len; i += 8) { + swap(buffer, i, i + 7) + swap(buffer, i + 1, i + 6) + swap(buffer, i + 2, i + 5) + swap(buffer, i + 3, i + 4) + } + + return buffer +} + +function toBuffer (buffer) { + return buffer +} + +function toString (buffer, encoding, start = 0, end = buffer.byteLength) { + const len = buffer.byteLength + + if (start >= len) return '' + if (end <= start) return '' + if (start < 0) start = 0 + if (end > len) end = len + + if (start !== 0 || end < len) buffer = buffer.subarray(start, end) + + return codecFor(encoding).toString(buffer) +} + +function write (buffer, string, offset, length, encoding) { + // write(buffer, string) + if (offset === undefined) { + encoding = 'utf8' + + // write(buffer, string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + + // write(buffer, string, offset, encoding) + } else if (encoding === undefined && typeof length === 'string') { + encoding = length + length = undefined + } + + return codecFor(encoding).write(buffer, string, offset, length) +} + +function writeDoubleLE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat64(offset, value, true) + + return offset + 8 +} + +function writeFloatLE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat32(offset, value, true) + + return offset + 4 +} + +function writeUInt32LE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setUint32(offset, value, true) + + return offset + 4 +} + +function writeInt32LE (buffer, value, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setInt32(offset, value, true) + + return offset + 4 +} + +function readDoubleLE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getFloat64(offset, true) +} + +function readFloatLE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getFloat32(offset, true) +} + +function readUInt32LE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getUint32(offset, true) +} + +function readInt32LE (buffer, offset) { + if (offset === undefined) offset = 0 + + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + + return view.getInt32(offset, true) +} + +module.exports = exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE +} + + +/***/ }), + +/***/ 6209: +/***/ ((module) => { + +function byteLength (string) { + return string.length +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i++) { + result += String.fromCharCode(buffer[i]) + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0; i < len; i++) { + buffer[offset + i] = string.charCodeAt(i) + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 943: +/***/ ((module) => { + +const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +const codes = new Uint8Array(256) + +for (let i = 0; i < alphabet.length; i++) { + codes[alphabet.charCodeAt(i)] = i +} + +codes[/* - */ 0x2d] = 62 +codes[/* _ */ 0x5f] = 63 + +function byteLength (string) { + let len = string.length + + if (string.charCodeAt(len - 1) === 0x3d) len-- + if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len-- + + return (len * 3) >>> 2 +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i += 3) { + result += ( + alphabet[buffer[i] >> 2] + + alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] + + alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] + + alphabet[buffer[i + 2] & 63] + ) + } + + if (len % 3 === 2) { + result = result.substring(0, result.length - 1) + '=' + } else if (len % 3 === 1) { + result = result.substring(0, result.length - 2) + '==' + } + + return result +}; + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0, j = 0; j < len; i += 4) { + const a = codes[string.charCodeAt(i)] + const b = codes[string.charCodeAt(i + 1)] + const c = codes[string.charCodeAt(i + 2)] + const d = codes[string.charCodeAt(i + 3)] + + buffer[j++] = (a << 2) | (b >> 4) + buffer[j++] = ((b & 15) << 4) | (c >> 2) + buffer[j++] = ((c & 3) << 6) | (d & 63) + } + + return len +}; + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 1847: +/***/ ((module) => { + +function byteLength (string) { + return string.length >>> 1 +} + +function toString (buffer) { + const len = buffer.byteLength + + buffer = new DataView(buffer.buffer, buffer.byteOffset, len) + + let result = '' + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + result += buffer.getUint32(i).toString(16).padStart(8, '0') + } + + for (; i < len; i++) { + result += buffer.getUint8(i).toString(16).padStart(2, '0') + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + for (let i = 0; i < len; i++) { + const a = hexValue(string.charCodeAt(i * 2)) + const b = hexValue(string.charCodeAt(i * 2 + 1)) + + if (a === undefined || b === undefined) { + return buffer.subarray(0, i) + } + + buffer[offset + i] = (a << 4) | b + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + +function hexValue (char) { + if (char >= 0x30 && char <= 0x39) return char - 0x30 + if (char >= 0x41 && char <= 0x46) return char - 0x41 + 10 + if (char >= 0x61 && char <= 0x66) return char - 0x61 + 10 +} + + +/***/ }), + +/***/ 5435: +/***/ ((module) => { + +function byteLength (string) { + return string.length * 2 +} + +function toString (buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len - 1; i += 2) { + result += String.fromCharCode(buffer[i] + (buffer[i + 1] * 256)) + } + + return result +} + +function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + let units = len + + for (let i = 0; i < string.length; ++i) { + if ((units -= 2) < 0) break + + const c = string.charCodeAt(i) + const hi = c >> 8 + const lo = c % 256 + + buffer[offset + i * 2] = lo + buffer[offset + i * 2 + 1] = hi + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 6679: +/***/ ((module) => { + +function byteLength (string) { + let length = 0 + + for (let i = 0, n = string.length; i < n; i++) { + const code = string.charCodeAt(i) + + if (code >= 0xd800 && code <= 0xdbff && i + 1 < n) { + const code = string.charCodeAt(i + 1) + + if (code >= 0xdc00 && code <= 0xdfff) { + length += 4 + i++ + continue + } + } + + if (code <= 0x7f) length += 1 + else if (code <= 0x7ff) length += 2 + else length += 3 + } + + return length +} + +let toString + +if (typeof TextDecoder !== 'undefined') { + const decoder = new TextDecoder() + + toString = function toString (buffer) { + return decoder.decode(buffer) + } +} else { + toString = function toString (buffer) { + const len = buffer.byteLength + + let output = '' + let i = 0 + + while (i < len) { + let byte = buffer[i] + + if (byte <= 0x7f) { + output += String.fromCharCode(byte) + i++ + continue + } + + let bytesNeeded = 0 + let codePoint = 0 + + if (byte <= 0xdf) { + bytesNeeded = 1 + codePoint = byte & 0x1f + } else if (byte <= 0xef) { + bytesNeeded = 2 + codePoint = byte & 0x0f + } else if (byte <= 0xf4) { + bytesNeeded = 3 + codePoint = byte & 0x07 + } + + if (len - i - bytesNeeded > 0) { + let k = 0 + + while (k < bytesNeeded) { + byte = buffer[i + k + 1] + codePoint = (codePoint << 6) | (byte & 0x3f) + k += 1 + } + } else { + codePoint = 0xfffd + bytesNeeded = len - i + } + + output += String.fromCodePoint(codePoint) + i += bytesNeeded + 1 + } + + return output + } +} + +let write + +if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder() + + write = function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + encoder.encodeInto(string, buffer.subarray(offset, offset + len)) + return len + } +} else { + write = function write (buffer, string, offset = 0, length = byteLength(string)) { + const len = Math.min(length, buffer.byteLength - offset) + + buffer = buffer.subarray(offset, offset + len) + + let i = 0 + let j = 0 + + while (i < string.length) { + const code = string.codePointAt(i) + + if (code <= 0x7f) { + buffer[j++] = code + i++ + continue + } + + let count = 0 + let bits = 0 + + if (code <= 0x7ff) { + count = 6 + bits = 0xc0 + } else if (code <= 0xffff) { + count = 12 + bits = 0xe0 + } else if (code <= 0x1fffff) { + count = 18 + bits = 0xf0 + } + + buffer[j++] = bits | (code >> count) + count -= 6 + + while (count >= 0) { + buffer[j++] = 0x80 | ((code >> count) & 0x3f) + count -= 6 + } + + i += code >= 0x10000 ? 2 : 1 + } + + return len + } +} + +module.exports = { + byteLength, + toString, + write +} + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 2096: +/***/ ((module, exports, __webpack_require__) => { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + } + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + } + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + } + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + } + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + } + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + } + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + } + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + } + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + } + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + } + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + } + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + } + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + } + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, t, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + } + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + } + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + } + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + } + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; +})(); + +// Node.js check +if ( true && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +//amd check +if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return bigInt; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); +} + + +/***/ }), + +/***/ 654: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(5702)(__webpack_require__(6989)) + + +/***/ }), + +/***/ 4315: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +const Transform = (__webpack_require__(8399).Transform) + +module.exports = class Blake extends Transform { + constructor (engine, options) { + super(options) + + this._engine = engine + this._finalized = false + } + + _transform (chunk, encoding, callback) { + let error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + _flush (callback) { + let error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + update (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._engine.update(data) + + return this + } + + digest (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + let digest = this._engine.digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + return digest + } +} + + +/***/ }), + +/***/ 5702: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Blake = __webpack_require__(4315) + +module.exports = (engines) => { + const getEngine = (algorithm) => { + const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm + switch (hash) { + case 'blake224': return engines.Blake224 + case 'blake256': return engines.Blake256 + case 'blake384': return engines.Blake384 + case 'blake512': return engines.Blake512 + + default: throw new Error('Invald algorithm: ' + algorithm) + } + } + + return (algorithm, options) => { + const Engine = getEngine(algorithm) + return new Blake(new Engine(), options) + } +} + + +/***/ }), + +/***/ 4588: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +class Blake { + _lengthCarry (arr) { + for (let j = 0; j < arr.length; ++j) { + if (arr[j] < 0x0100000000) break + arr[j] -= 0x0100000000 + arr[j + 1] += 1 + } + } + + update (data) { + const block = this._block + let offset = 0 + + while (this._blockOffset + data.length - offset >= block.length) { + for (let i = this._blockOffset; i < block.length;) block[i++] = data[offset++] + + this._length[0] += block.length * 8 + this._lengthCarry(this._length) + + this._compress() + this._blockOffset = 0 + } + + while (offset < data.length) block[this._blockOffset++] = data[offset++] + } +} + +Blake.sigma = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], + [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], + [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], + [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], + [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], + [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], + [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], + [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], + [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], + [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], + [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], + [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], + [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9] +] + +Blake.u256 = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917 +] + +Blake.u512 = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, + 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69 +] + +Blake.padding = Buffer.from([ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +]) + +module.exports = Blake + + +/***/ }), + +/***/ 8746: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +const Blake256 = __webpack_require__(3287) + +const zo = Buffer.from([0x00]) +const oo = Buffer.from([0x80]) + +module.exports = class Blake224 extends Blake256 { + constructor () { + super() + + this._h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ] + + this._zo = zo + this._oo = oo + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(28) + for (let i = 0; i < 7; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 3287: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +const Blake = __webpack_require__(4588) + +const zo = Buffer.from([0x01]) +const oo = Buffer.from([0x81]) + +const rot = (x, n) => ((x << (32 - n)) | (x >>> n)) >>> 0 + +function g (v, m, i, a, b, c, d, e) { + const sigma = Blake.sigma + const u256 = Blake.u256 + + v[a] = (v[a] + ((m[sigma[i][e]] ^ u256[sigma[i][e + 1]]) >>> 0) + v[b]) >>> 0 + v[d] = rot(v[d] ^ v[a], 16) + v[c] = (v[c] + v[d]) >>> 0 + v[b] = rot(v[b] ^ v[c], 12) + v[a] = (v[a] + ((m[sigma[i][e + 1]] ^ u256[sigma[i][e]]) >>> 0) + v[b]) >>> 0 + v[d] = rot(v[d] ^ v[a], 8) + v[c] = (v[c] + v[d]) >>> 0 + v[b] = rot(v[b] ^ v[c], 7) +} + +module.exports = class Blake256 extends Blake { + constructor () { + super() + + this._h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ] + + this._s = [0, 0, 0, 0] + + this._block = Buffer.alloc(64) + this._blockOffset = 0 + this._length = [0, 0] + + this._nullt = false + + this._zo = zo + this._oo = oo + } + + _compress () { + const u256 = Blake.u256 + const v = new Array(16) + const m = new Array(16) + let i + + for (i = 0; i < 16; ++i) m[i] = this._block.readUInt32BE(i * 4) + for (i = 0; i < 8; ++i) v[i] = this._h[i] >>> 0 + for (i = 8; i < 12; ++i) v[i] = (this._s[i - 8] ^ u256[i - 8]) >>> 0 + for (i = 12; i < 16; ++i) v[i] = u256[i - 8] + + if (!this._nullt) { + v[12] = (v[12] ^ this._length[0]) >>> 0 + v[13] = (v[13] ^ this._length[0]) >>> 0 + v[14] = (v[14] ^ this._length[1]) >>> 0 + v[15] = (v[15] ^ this._length[1]) >>> 0 + } + + for (i = 0; i < 14; ++i) { + /* column step */ + g(v, m, i, 0, 4, 8, 12, 0) + g(v, m, i, 1, 5, 9, 13, 2) + g(v, m, i, 2, 6, 10, 14, 4) + g(v, m, i, 3, 7, 11, 15, 6) + /* diagonal step */ + g(v, m, i, 0, 5, 10, 15, 8) + g(v, m, i, 1, 6, 11, 12, 10) + g(v, m, i, 2, 7, 8, 13, 12) + g(v, m, i, 3, 4, 9, 14, 14) + } + + for (i = 0; i < 16; ++i) this._h[i % 8] = (this._h[i % 8] ^ v[i]) >>> 0 + for (i = 0; i < 8; ++i) this._h[i] = (this._h[i] ^ this._s[i % 4]) >>> 0 + } + + _padding () { + let lo = this._length[0] + this._blockOffset * 8 + let hi = this._length[1] + if (lo >= 0x0100000000) { + lo -= 0x0100000000 + hi += 1 + } + + const msglen = Buffer.alloc(8) + msglen.writeUInt32BE(hi, 0) + msglen.writeUInt32BE(lo, 4) + + if (this._blockOffset === 55) { + this._length[0] -= 8 + this.update(this._oo) + } else { + if (this._blockOffset < 55) { + if (this._blockOffset === 0) this._nullt = true + this._length[0] -= (55 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 55 - this._blockOffset)) + } else { + this._length[0] -= (64 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 64 - this._blockOffset)) + this._length[0] -= 55 * 8 + this.update(Blake.padding.slice(1, 1 + 55)) + this._nullt = true + } + + this.update(this._zo) + this._length[0] -= 8 + } + + this._length[0] -= 64 + this.update(msglen) + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(32) + for (let i = 0; i < 8; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 399: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +const Blake512 = __webpack_require__(1070) + +const zo = Buffer.from([0x00]) +const oo = Buffer.from([0x80]) + +module.exports = class Blake384 extends Blake512 { + constructor () { + super() + + this._h = [ + 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 + ] + + this._zo = zo + this._oo = oo + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(48) + for (let i = 0; i < 12; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 1070: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +const Blake = __webpack_require__(4588) + +const zo = Buffer.from([0x01]) +const oo = Buffer.from([0x81]) + +function rot (v, i, j, n) { + let hi = v[i * 2] ^ v[j * 2] + let lo = v[i * 2 + 1] ^ v[j * 2 + 1] + + if (n >= 32) { + lo = lo ^ hi + hi = lo ^ hi + lo = lo ^ hi + n -= 32 + } + + if (n === 0) { + v[i * 2] = hi >>> 0 + v[i * 2 + 1] = lo >>> 0 + } else { + v[i * 2] = ((hi >>> n) | (lo << (32 - n))) >>> 0 + v[i * 2 + 1] = ((lo >>> n) | (hi << (32 - n))) >>> 0 + } +} + +function g (v, m, i, a, b, c, d, e) { + const sigma = Blake.sigma + const u512 = Blake.u512 + let lo + + // v[a] += (m[sigma[i][e]] ^ u512[sigma[i][e+1]]) + v[b]; + lo = v[a * 2 + 1] + ((m[sigma[i][e] * 2 + 1] ^ u512[sigma[i][e + 1] * 2 + 1]) >>> 0) + v[b * 2 + 1] + v[a * 2] = (v[a * 2] + ((m[sigma[i][e] * 2] ^ u512[sigma[i][e + 1] * 2]) >>> 0) + v[b * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[a * 2 + 1] = lo >>> 0 + + // v[d] = ROT( v[d] ^ v[a],32); + rot(v, d, a, 32) + + // v[c] += v[d]; + lo = v[c * 2 + 1] + v[d * 2 + 1] + v[c * 2] = (v[c * 2] + v[d * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[c * 2 + 1] = lo >>> 0 + + // v[b] = ROT( v[b] ^ v[c],25); + rot(v, b, c, 25) + + // v[a] += (m[sigma[i][e+1]] ^ u512[sigma[i][e]])+v[b]; + lo = v[a * 2 + 1] + ((m[sigma[i][e + 1] * 2 + 1] ^ u512[sigma[i][e] * 2 + 1]) >>> 0) + v[b * 2 + 1] + v[a * 2] = (v[a * 2] + ((m[sigma[i][e + 1] * 2] ^ u512[sigma[i][e] * 2]) >>> 0) + v[b * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[a * 2 + 1] = lo >>> 0 + + // v[d] = ROT( v[d] ^ v[a],16); + rot(v, d, a, 16) + + // v[c] += v[d]; + lo = v[c * 2 + 1] + v[d * 2 + 1] + v[c * 2] = (v[c * 2] + v[d * 2] + ~~(lo / 0x0100000000)) >>> 0 + v[c * 2 + 1] = lo >>> 0 + + // v[b] = ROT( v[b] ^ v[c],11) + rot(v, b, c, 11) +} + +module.exports = class Blake512 extends Blake { + constructor () { + super() + + this._h = [ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 + ] + + this._s = [0, 0, 0, 0, 0, 0, 0, 0] + + this._block = Buffer.alloc(128) + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._nullt = false + + this._zo = zo + this._oo = oo + } + + _compress () { + const u512 = Blake.u512 + const v = new Array(32) + const m = new Array(32) + let i + + for (i = 0; i < 32; ++i) m[i] = this._block.readUInt32BE(i * 4) + for (i = 0; i < 16; ++i) v[i] = this._h[i] >>> 0 + for (i = 16; i < 24; ++i) v[i] = (this._s[i - 16] ^ u512[i - 16]) >>> 0 + for (i = 24; i < 32; ++i) v[i] = u512[i - 16] + + if (!this._nullt) { + v[24] = (v[24] ^ this._length[1]) >>> 0 + v[25] = (v[25] ^ this._length[0]) >>> 0 + v[26] = (v[26] ^ this._length[1]) >>> 0 + v[27] = (v[27] ^ this._length[0]) >>> 0 + v[28] = (v[28] ^ this._length[3]) >>> 0 + v[29] = (v[29] ^ this._length[2]) >>> 0 + v[30] = (v[30] ^ this._length[3]) >>> 0 + v[31] = (v[31] ^ this._length[2]) >>> 0 + } + + for (i = 0; i < 16; ++i) { + /* column step */ + g(v, m, i, 0, 4, 8, 12, 0) + g(v, m, i, 1, 5, 9, 13, 2) + g(v, m, i, 2, 6, 10, 14, 4) + g(v, m, i, 3, 7, 11, 15, 6) + /* diagonal step */ + g(v, m, i, 0, 5, 10, 15, 8) + g(v, m, i, 1, 6, 11, 12, 10) + g(v, m, i, 2, 7, 8, 13, 12) + g(v, m, i, 3, 4, 9, 14, 14) + } + + for (i = 0; i < 16; ++i) { + this._h[(i % 8) * 2] = (this._h[(i % 8) * 2] ^ v[i * 2]) >>> 0 + this._h[(i % 8) * 2 + 1] = (this._h[(i % 8) * 2 + 1] ^ v[i * 2 + 1]) >>> 0 + } + + for (i = 0; i < 8; ++i) { + this._h[i * 2] = (this._h[i * 2] ^ this._s[(i % 4) * 2]) >>> 0 + this._h[i * 2 + 1] = (this._h[i * 2 + 1] ^ this._s[(i % 4) * 2 + 1]) >>> 0 + } + } + + _padding () { + const len = this._length.slice() + len[0] += this._blockOffset * 8 + this._lengthCarry(len) + + const msglen = Buffer.alloc(16) + for (let i = 0; i < 4; ++i) msglen.writeUInt32BE(len[3 - i], i * 4) + + if (this._blockOffset === 111) { + this._length[0] -= 8 + this.update(this._oo) + } else { + if (this._blockOffset < 111) { + if (this._blockOffset === 0) this._nullt = true + this._length[0] -= (111 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 111 - this._blockOffset)) + } else { + this._length[0] -= (128 - this._blockOffset) * 8 + this.update(Blake.padding.slice(0, 128 - this._blockOffset)) + this._length[0] -= 111 * 8 + this.update(Blake.padding.slice(1, 1 + 111)) + this._nullt = true + } + + this.update(this._zo) + this._length[0] -= 8 + } + + this._length[0] -= 128 + this.update(msglen) + } + + digest () { + this._padding() + + const buffer = Buffer.alloc(64) + for (let i = 0; i < 16; ++i) buffer.writeUInt32BE(this._h[i], i * 4) + return buffer + } +} + + +/***/ }), + +/***/ 6989: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = { + Blake224: __webpack_require__(8746), + Blake256: __webpack_require__(3287), + Blake384: __webpack_require__(399), + Blake512: __webpack_require__(1070) +} + + +/***/ }), + +/***/ 1892: +/***/ ((module) => { + +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __toBinary = /* @__PURE__ */ (() => { + var table = new Uint8Array(128); + for (var i = 0; i < 64; i++) + table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i; + return (base64) => { + var n = base64.length, bytes2 = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0); + for (var i2 = 0, j = 0; i2 < n; ) { + var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)]; + var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)]; + bytes2[j++] = c0 << 2 | c1 >> 4; + bytes2[j++] = c1 << 4 | c2 >> 2; + bytes2[j++] = c2 << 6 | c3; + } + return bytes2; + }; +})(); + +// wasm-binary:./blake2b.wat +var require_blake2b = __commonJS({ + "wasm-binary:./blake2b.wat"(exports2, module2) { + module2.exports = __toBinary("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs="); + } +}); + +// wasm-module:./blake2b.wat +var bytes = require_blake2b(); +var compiled = WebAssembly.compile(bytes); +module.exports = async (imports) => { + const instance = await WebAssembly.instantiate(await compiled, imports); + return instance.exports; +}; + + +/***/ }), + +/***/ 1685: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var assert = __webpack_require__(6889) +var b4a = __webpack_require__(5682) + +var wasm = null +var wasmPromise = typeof WebAssembly !== "undefined" && __webpack_require__(1892)().then(mod => { + wasm = mod +}) + +var head = 64 +var freeList = [] + +module.exports = Blake2b +var BYTES_MIN = module.exports.BYTES_MIN = 16 +var BYTES_MAX = module.exports.BYTES_MAX = 64 +var BYTES = module.exports.BYTES = 32 +var KEYBYTES_MIN = module.exports.KEYBYTES_MIN = 16 +var KEYBYTES_MAX = module.exports.KEYBYTES_MAX = 64 +var KEYBYTES = module.exports.KEYBYTES = 32 +var SALTBYTES = module.exports.SALTBYTES = 16 +var PERSONALBYTES = module.exports.PERSONALBYTES = 16 + +function Blake2b (digestLength, key, salt, personal, noAssert) { + if (!(this instanceof Blake2b)) return new Blake2b(digestLength, key, salt, personal, noAssert) + if (!wasm) throw new Error('WASM not loaded. Wait for Blake2b.ready(cb)') + if (!digestLength) digestLength = 32 + + if (noAssert !== true) { + assert(digestLength >= BYTES_MIN, 'digestLength must be at least ' + BYTES_MIN + ', was given ' + digestLength) + assert(digestLength <= BYTES_MAX, 'digestLength must be at most ' + BYTES_MAX + ', was given ' + digestLength) + if (key != null) { + assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer') + assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length) + assert(key.length <= KEYBYTES_MAX, 'key must be at least ' + KEYBYTES_MAX + ', was given ' + key.length) + } + if (salt != null) { + assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer') + assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length) + } + if (personal != null) { + assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer') + assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length) + } + } + + if (!freeList.length) { + freeList.push(head) + head += 216 + } + + this.digestLength = digestLength + this.finalized = false + this.pointer = freeList.pop() + this._memory = new Uint8Array(wasm.memory.buffer) + + this._memory.fill(0, 0, 64) + this._memory[0] = this.digestLength + this._memory[1] = key ? key.length : 0 + this._memory[2] = 1 // fanout + this._memory[3] = 1 // depth + + if (salt) this._memory.set(salt, 32) + if (personal) this._memory.set(personal, 48) + + if (this.pointer + 216 > this._memory.length) this._realloc(this.pointer + 216) // we need 216 bytes for the state + wasm.blake2b_init(this.pointer, this.digestLength) + + if (key) { + this.update(key) + this._memory.fill(0, head, head + key.length) // whiteout key + this._memory[this.pointer + 200] = 128 + } +} + +Blake2b.prototype._realloc = function (size) { + wasm.memory.grow(Math.max(0, Math.ceil(Math.abs(size - this._memory.length) / 65536))) + this._memory = new Uint8Array(wasm.memory.buffer) +} + +Blake2b.prototype.update = function (input) { + assert(this.finalized === false, 'Hash instance finalized') + assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer') + + if (head + input.length > this._memory.length) this._realloc(head + input.length) + this._memory.set(input, head) + wasm.blake2b_update(this.pointer, head, head + input.length) + return this +} + +Blake2b.prototype.digest = function (enc) { + assert(this.finalized === false, 'Hash instance finalized') + this.finalized = true + + freeList.push(this.pointer) + wasm.blake2b_final(this.pointer) + + if (!enc || enc === 'binary') { + return this._memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength) + } + + if (typeof enc === 'string') { + return b4a.toString(this._memory, enc, this.pointer + 128, this.pointer + 128 + this.digestLength) + } + + assert(enc instanceof Uint8Array && enc.length >= this.digestLength, 'input must be Uint8Array or Buffer') + for (var i = 0; i < this.digestLength; i++) { + enc[i] = this._memory[this.pointer + 128 + i] + } + + return enc +} + +// libsodium compat +Blake2b.prototype.final = Blake2b.prototype.digest + +Blake2b.WASM = wasm +Blake2b.SUPPORTED = typeof WebAssembly !== 'undefined' + +Blake2b.ready = function (cb) { + if (!cb) cb = noop + if (!wasmPromise) return cb(new Error('WebAssembly not supported')) + return wasmPromise.then(() => cb(), cb) +} + +Blake2b.prototype.ready = Blake2b.ready + +Blake2b.prototype.getPartialHash = function () { + return this._memory.slice(this.pointer, this.pointer + 216); +} + +Blake2b.prototype.setPartialHash = function (ph) { + this._memory.set(ph, this.pointer); +} + +function noop () {} + + +/***/ }), + +/***/ 2206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var assert = __webpack_require__(6889) +var b2wasm = __webpack_require__(1685) + +// 64-bit unsigned addition +// Sets v[a,a+1] += v[b,b+1] +// v should be a Uint32Array +function ADD64AA (v, a, b) { + var o0 = v[a] + v[b] + var o1 = v[a + 1] + v[b + 1] + if (o0 >= 0x100000000) { + o1++ + } + v[a] = o0 + v[a + 1] = o1 +} + +// 64-bit unsigned addition +// Sets v[a,a+1] += b +// b0 is the low 32 bits of b, b1 represents the high 32 bits +function ADD64AC (v, a, b0, b1) { + var o0 = v[a] + b0 + if (b0 < 0) { + o0 += 0x100000000 + } + var o1 = v[a + 1] + b1 + if (o0 >= 0x100000000) { + o1++ + } + v[a] = o0 + v[a + 1] = o1 +} + +// Little-endian byte access +function B2B_GET32 (arr, i) { + return (arr[i] ^ + (arr[i + 1] << 8) ^ + (arr[i + 2] << 16) ^ + (arr[i + 3] << 24)) +} + +// G Mixing function +// The ROTRs are inlined for speed +function B2B_G (a, b, c, d, ix, iy) { + var x0 = m[ix] + var x1 = m[ix + 1] + var y0 = m[iy] + var y1 = m[iy + 1] + + ADD64AA(v, a, b) // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s + ADD64AC(v, a, x0, x1) // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + var xor0 = v[d] ^ v[a] + var xor1 = v[d + 1] ^ v[a + 1] + v[d] = xor1 + v[d + 1] = xor0 + + ADD64AA(v, c, d) + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c] + xor1 = v[b + 1] ^ v[c + 1] + v[b] = (xor0 >>> 24) ^ (xor1 << 8) + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8) + + ADD64AA(v, a, b) + ADD64AC(v, a, y0, y1) + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a] + xor1 = v[d + 1] ^ v[a + 1] + v[d] = (xor0 >>> 16) ^ (xor1 << 16) + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16) + + ADD64AA(v, c, d) + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c] + xor1 = v[b + 1] ^ v[c + 1] + v[b] = (xor1 >>> 31) ^ (xor0 << 1) + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1) +} + +// Initialization Vector +var BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]) + +var SIGMA8 = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +] + +// These are offsets into a uint64 buffer. +// Multiply them all by 2 to make them offsets into a uint32 buffer, +// because this is Javascript and we don't have uint64s +var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 })) + +// Compression function. 'last' flag indicates last block. +// Note we're representing 16 uint64s as 32 uint32s +var v = new Uint32Array(32) +var m = new Uint32Array(32) +function blake2bCompress (ctx, last) { + var i = 0 + + // init work variables + for (i = 0; i < 16; i++) { + v[i] = ctx.h[i] + v[i + 16] = BLAKE2B_IV32[i] + } + + // low 64 bits of offset + v[24] = v[24] ^ ctx.t + v[25] = v[25] ^ (ctx.t / 0x100000000) + // high 64 bits not supported, offset may not be higher than 2**53-1 + + // last block flag set ? + if (last) { + v[28] = ~v[28] + v[29] = ~v[29] + } + + // get little-endian words + for (i = 0; i < 32; i++) { + m[i] = B2B_GET32(ctx.b, 4 * i) + } + + // twelve rounds of mixing + for (i = 0; i < 12; i++) { + B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]) + B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]) + B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]) + B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]) + B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]) + B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]) + B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]) + B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]) + } + + for (i = 0; i < 16; i++) { + ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16] + } +} + +// reusable parameter_block +var parameter_block = new Uint8Array([ + 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth + 0, 0, 0, 0, // 4: leaf length, sequential mode + 0, 0, 0, 0, // 8: node offset + 0, 0, 0, 0, // 12: node offset + 0, 0, 0, 0, // 16: node depth, inner length, rfu + 0, 0, 0, 0, // 20: rfu + 0, 0, 0, 0, // 24: rfu + 0, 0, 0, 0, // 28: rfu + 0, 0, 0, 0, // 32: salt + 0, 0, 0, 0, // 36: salt + 0, 0, 0, 0, // 40: salt + 0, 0, 0, 0, // 44: salt + 0, 0, 0, 0, // 48: personal + 0, 0, 0, 0, // 52: personal + 0, 0, 0, 0, // 56: personal + 0, 0, 0, 0 // 60: personal +]) + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +function Blake2b (outlen, key, salt, personal) { + // zero out parameter_block before usage + parameter_block.fill(0) + // state, 'param block' + + this.b = new Uint8Array(128) + this.h = new Uint32Array(16) + this.t = 0 // input count + this.c = 0 // pointer within buffer + this.outlen = outlen // output length in bytes + + parameter_block[0] = outlen + if (key) parameter_block[1] = key.length + parameter_block[2] = 1 // fanout + parameter_block[3] = 1 // depth + + if (salt) parameter_block.set(salt, 32) + if (personal) parameter_block.set(personal, 48) + + // initialize hash state + for (var i = 0; i < 16; i++) { + this.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameter_block, i * 4) + } + + // key the hash, if applicable + if (key) { + blake2bUpdate(this, key) + // at the end + this.c = 128 + } +} + +Blake2b.prototype.update = function (input) { + assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer') + blake2bUpdate(this, input) + return this +} + +Blake2b.prototype.digest = function (out) { + var buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out + assert(buf instanceof Uint8Array, 'out must be "binary", "hex", Uint8Array, or Buffer') + assert(buf.length >= this.outlen, 'out must have at least outlen bytes of space') + blake2bFinal(this, buf) + if (out === 'hex') return hexSlice(buf) + return buf +} + +Blake2b.prototype.final = Blake2b.prototype.digest + +Blake2b.ready = function (cb) { + b2wasm.ready(function () { + cb() // ignore the error + }) +} + +// Updates a BLAKE2b streaming hash +// Requires hash context and Uint8Array (byte array) +function blake2bUpdate (ctx, input) { + for (var i = 0; i < input.length; i++) { + if (ctx.c === 128) { // buffer full ? + ctx.t += ctx.c // add counters + blake2bCompress(ctx, false) // compress (not last) + ctx.c = 0 // counter to zero + } + ctx.b[ctx.c++] = input[i] + } +} + +// Completes a BLAKE2b streaming hash +// Returns a Uint8Array containing the message digest +function blake2bFinal (ctx, out) { + ctx.t += ctx.c // mark last block offset + + while (ctx.c < 128) { // fill up with zeros + ctx.b[ctx.c++] = 0 + } + blake2bCompress(ctx, true) // final block flag = 1 + + for (var i = 0; i < ctx.outlen; i++) { + out[i] = ctx.h[i >> 2] >> (8 * (i & 3)) + } + return out +} + +function hexSlice (buf) { + var str = '' + for (var i = 0; i < buf.length; i++) str += toHex(buf[i]) + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +var Proto = Blake2b + +module.exports = function createHash (outlen, key, salt, personal, noAssert) { + if (noAssert !== true) { + assert(outlen >= BYTES_MIN, 'outlen must be at least ' + BYTES_MIN + ', was given ' + outlen) + assert(outlen <= BYTES_MAX, 'outlen must be at most ' + BYTES_MAX + ', was given ' + outlen) + if (key != null) { + assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer') + assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length) + assert(key.length <= KEYBYTES_MAX, 'key must be at most ' + KEYBYTES_MAX + ', was given ' + key.length) + } + if (salt != null) { + assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer') + assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length) + } + if (personal != null) { + assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer') + assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length) + } + } + + return new Proto(outlen, key, salt, personal) +} + +module.exports.ready = function (cb) { + b2wasm.ready(function () { // ignore errors + cb() + }) +} + +module.exports.WASM_SUPPORTED = b2wasm.SUPPORTED +module.exports.WASM_LOADED = false + +var BYTES_MIN = module.exports.BYTES_MIN = 16 +var BYTES_MAX = module.exports.BYTES_MAX = 64 +var BYTES = module.exports.BYTES = 32 +var KEYBYTES_MIN = module.exports.KEYBYTES_MIN = 16 +var KEYBYTES_MAX = module.exports.KEYBYTES_MAX = 64 +var KEYBYTES = module.exports.KEYBYTES = 32 +var SALTBYTES = module.exports.SALTBYTES = 16 +var PERSONALBYTES = module.exports.PERSONALBYTES = 16 + +b2wasm.ready(function (err) { + if (!err) { + module.exports.WASM_LOADED = true + module.exports = b2wasm + } +}) + + +/***/ }), + +/***/ 9404: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(7790).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this._strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // '0' - '9' + if (c >= 48 && c <= 57) { + return c - 48; + // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this._strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + b = c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; + + // '0' - '9' + } else { + b = c; + } + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this._strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + function move (dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } + + BN.prototype._move = function _move (dest) { + move(dest, this); + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype._strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility + if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { + try { + BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; + } + } else { + BN.prototype.inspect = inspect; + } + + function inspect () { + return (this.red ? ''; + } + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16, 2); + }; + + if (Buffer) { + BN.prototype.toBuffer = function toBuffer (endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + var allocate = function allocate (ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; + }; + + BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { + var position = 0; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = (word >> 8) & 0xff; + } + if (position < res.length) { + res[position++] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position < res.length) { + res[position++] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position < res.length) { + res[position++] = carry; + + while (position < res.length) { + res[position++] = 0; + } + } + }; + + BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { + var position = res.length - 1; + var carry = 0; + + for (var i = 0, shift = 0; i < this.length; i++) { + var word = (this.words[i] << shift) | carry; + + res[position--] = word & 0xff; + if (position >= 0) { + res[position--] = (word >> 8) & 0xff; + } + if (position >= 0) { + res[position--] = (word >> 16) & 0xff; + } + + if (shift === 6) { + if (position >= 0) { + res[position--] = (word >> 24) & 0xff; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + + if (position >= 0) { + res[position--] = carry; + + while (position >= 0) { + res[position--] = 0; + } + } + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] >>> wbit) & 0x01; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this._strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this._strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this._strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this._strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this._strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this._strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out._strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out._strip(); + } + + function jumboMulTo (self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out._strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this._strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this._strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this._strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this._strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this._strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this._strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modrn = function modrn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return isNegNum ? -acc : acc; + }; + + // WARNING: DEPRECATED + BN.prototype.modn = function modn (num) { + return this.modrn(num); + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + this._strip(); + return isNegNum ? this.ineg() : this; + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this._strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 5037: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + +if (typeof self === 'object') { + if (self.crypto && self.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker with no crypto support + try { + var crypto = __webpack_require__(3776); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } +} + + +/***/ }), + +/***/ 462: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var Buffer = (__webpack_require__(2861).Buffer) + +function asUInt32Array (buf) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + + var len = (buf.length / 4) | 0 + var out = new Array(len) + + for (var i = 0; i < len; i++) { + out[i] = buf.readUInt32BE(i * 4) + } + + return out +} + +function scrubVec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } +} + +function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { + var SUB_MIX0 = SUB_MIX[0] + var SUB_MIX1 = SUB_MIX[1] + var SUB_MIX2 = SUB_MIX[2] + var SUB_MIX3 = SUB_MIX[3] + + var s0 = M[0] ^ keySchedule[0] + var s1 = M[1] ^ keySchedule[1] + var s2 = M[2] ^ keySchedule[2] + var s3 = M[3] ^ keySchedule[3] + var t0, t1, t2, t3 + var ksRow = 4 + + for (var round = 1; round < nRounds; round++) { + t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + t1 = t1 >>> 0 + t2 = t2 >>> 0 + t3 = t3 >>> 0 + + return [t0, t1, t2, t3] +} + +// AES constants +var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +var G = (function () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + d[j] = (j << 1) ^ 0x11b + } + } + + var SBOX = [] + var INV_SBOX = [] + var SUB_MIX = [[], [], [], []] + var INV_SUB_MIX = [[], [], [], []] + + // Walk GF(2^8) + var x = 0 + var xi = 0 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + SBOX[x] = sx + INV_SBOX[sx] = x + + // Compute multiplication + var x2 = d[x] + var x4 = d[x2] + var x8 = d[x4] + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100) + SUB_MIX[0][x] = (t << 24) | (t >>> 8) + SUB_MIX[1][x] = (t << 16) | (t >>> 16) + SUB_MIX[2][x] = (t << 8) | (t >>> 24) + SUB_MIX[3][x] = t + + // Compute inv sub bytes, inv mix columns tables + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + INV_SUB_MIX[3][sx] = t + + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + INV_SUB_MIX: INV_SUB_MIX + } +})() + +function AES (key) { + this._key = asUInt32Array(key) + this._reset() +} + +AES.blockSize = 4 * 4 +AES.keySize = 256 / 8 +AES.prototype.blockSize = AES.blockSize +AES.prototype.keySize = AES.keySize +AES.prototype._reset = function () { + var keyWords = this._key + var keySize = keyWords.length + var nRounds = keySize + 6 + var ksRows = (nRounds + 1) * 4 + + var keySchedule = [] + for (var k = 0; k < keySize; k++) { + keySchedule[k] = keyWords[k] + } + + for (k = keySize; k < ksRows; k++) { + var t = keySchedule[k - 1] + + if (k % keySize === 0) { + t = (t << 8) | (t >>> 24) + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + + t ^= RCON[(k / keySize) | 0] << 24 + } else if (keySize > 6 && k % keySize === 4) { + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + } + + keySchedule[k] = keySchedule[k - keySize] ^ t + } + + var invKeySchedule = [] + for (var ik = 0; ik < ksRows; ik++) { + var ksR = ksRows - ik + var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] + + if (ik < 4 || ksR <= 4) { + invKeySchedule[ik] = tt + } else { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] + } + } + + this._nRounds = nRounds + this._keySchedule = keySchedule + this._invKeySchedule = invKeySchedule +} + +AES.prototype.encryptBlockRaw = function (M) { + M = asUInt32Array(M) + return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) +} + +AES.prototype.encryptBlock = function (M) { + var out = this.encryptBlockRaw(M) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = asUInt32Array(M) + + // swap + var m1 = M[1] + M[1] = M[3] + M[3] = m1 + + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrubVec(this._keySchedule) + scrubVec(this._invKeySchedule) + scrubVec(this._key) +} + +module.exports.AES = AES + + +/***/ }), + +/***/ 2356: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var aes = __webpack_require__(462) +var Buffer = (__webpack_require__(2861).Buffer) +var Transform = __webpack_require__(6168) +var inherits = __webpack_require__(6698) +var GHASH = __webpack_require__(5892) +var xor = __webpack_require__(295) +var incr32 = __webpack_require__(5122) + +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) out++ + + var len = Math.min(a.length, b.length) + for (var i = 0; i < len; ++i) { + out += (a[i] ^ b[i]) + } + + return out +} + +function calcIv (self, iv, ck) { + if (iv.length === 12) { + self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) + } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out +} +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + var h = Buffer.alloc(4, 0) + + this._cipher = new aes.AES(key) + var ck = this._cipher.encryptBlock(h) + this._ghash = new GHASH(ck) + iv = calcIv(this, iv, ck) + + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + this._mode = mode + + this._authTag = null + this._called = false +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) + } + } + + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} + +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') + + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') + + this._authTag = tag + this._cipher.scrub() +} + +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') + + return this._authTag +} + +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') + + this._authTag = tag +} + +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (this._called) throw new Error('Attempting to set AAD in unsupported state') + + this._ghash.update(buf) + this._alen += buf.length +} + +module.exports = StreamCipher + + +/***/ }), + +/***/ 1241: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ciphers = __webpack_require__(5799) +var deciphers = __webpack_require__(6171) +var modes = __webpack_require__(3219) + +function getCiphers () { + return Object.keys(modes) +} + +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + + +/***/ }), + +/***/ 6171: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var AuthCipher = __webpack_require__(2356) +var Buffer = (__webpack_require__(2861).Buffer) +var MODES = __webpack_require__(530) +var StreamCipher = __webpack_require__(650) +var Transform = __webpack_require__(6168) +var aes = __webpack_require__(462) +var ebtk = __webpack_require__(8078) +var inherits = __webpack_require__(6698) + +function Decipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Decipher, Transform) + +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} + +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} + +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + + return null +} + +Splitter.prototype.flush = function () { + if (this.cache.length) return this.cache +} + +function unpad (last) { + var padded = last[15] + if (padded < 1 || padded > 16) { + throw new Error('unable to decrypt data') + } + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) return + + return last.slice(0, 16 - padded) +} + +function createDecipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv, true) + } + + return new Decipher(config.module, password, iv) +} + +function createDecipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} + +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv + + +/***/ }), + +/***/ 5799: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var MODES = __webpack_require__(530) +var AuthCipher = __webpack_require__(2356) +var Buffer = (__webpack_require__(2861).Buffer) +var StreamCipher = __webpack_require__(650) +var Transform = __webpack_require__(6168) +var aes = __webpack_require__(462) +var ebtk = __webpack_require__(8078) +var inherits = __webpack_require__(6698) + +function Cipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Cipher, Transform) + +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + + return Buffer.concat(out) +} + +var PADDING = Buffer.alloc(16, 0x10) + +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } + + if (!chunk.equals(PADDING)) { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} + +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} + +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = Buffer.allocUnsafe(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + + return Buffer.concat([this.cache, padBuff]) +} + +function createCipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv) + } + + return new Cipher(config.module, password, iv) +} + +function createCipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher + + +/***/ }), + +/***/ 5892: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) +var ZEROES = Buffer.alloc(16, 0) + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} + +function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + buf.writeUInt32BE(out[3] >>> 0, 12) + return buf +} + +function GHASH (key) { + this.h = key + this.state = Buffer.alloc(16, 0) + this.cache = Buffer.allocUnsafe(0) +} + +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsbVi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + Zi[2] ^= Vi[2] + Zi[3] ^= Vi[3] + } + + // Store the value of LSB(V_i) + lsbVi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsbVi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} + +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} + +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, ZEROES], 16)) + } + + this.ghash(fromArray([0, abl, 0, bl])) + return this.state +} + +module.exports = GHASH + + +/***/ }), + +/***/ 5122: +/***/ ((module) => { + +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} +module.exports = incr32 + + +/***/ }), + +/***/ 2884: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var xor = __webpack_require__(295) + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} + + +/***/ }), + +/***/ 6383: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) +var xor = __webpack_require__(295) + +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} + +exports.encrypt = function (self, data, decrypt) { + var out = Buffer.allocUnsafe(0) + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = Buffer.allocUnsafe(0) + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} + + +/***/ }), + +/***/ 5264: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) + +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} + +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = Buffer.allocUnsafe(buffer.length) + buffer = Buffer.concat([buffer, Buffer.from([value])]) + + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + + +/***/ }), + +/***/ 6975: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) + +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + + self._prev = Buffer.concat([ + self._prev.slice(1), + Buffer.from([decrypt ? byteParam : out]) + ]) + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + + +/***/ }), + +/***/ 3053: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var xor = __webpack_require__(295) +var Buffer = (__webpack_require__(2861).Buffer) +var incr32 = __webpack_require__(5122) + +function getBlock (self) { + var out = self._cipher.encryptBlockRaw(self._prev) + incr32(self._prev) + return out +} + +var blockSize = 16 +exports.encrypt = function (self, chunk) { + var chunkNum = Math.ceil(chunk.length / blockSize) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + + +/***/ }), + +/***/ 2632: +/***/ ((__unused_webpack_module, exports) => { + +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} + +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} + + +/***/ }), + +/***/ 530: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var modeModules = { + ECB: __webpack_require__(2632), + CBC: __webpack_require__(2884), + CFB: __webpack_require__(6383), + CFB8: __webpack_require__(6975), + CFB1: __webpack_require__(5264), + OFB: __webpack_require__(6843), + CTR: __webpack_require__(3053), + GCM: __webpack_require__(3053) +} + +var modes = __webpack_require__(3219) + +for (var key in modes) { + modes[key].module = modeModules[modes[key].mode] +} + +module.exports = modes + + +/***/ }), + +/***/ 6843: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var xor = __webpack_require__(295) + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + + +/***/ }), + +/***/ 650: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var aes = __webpack_require__(462) +var Buffer = (__webpack_require__(2861).Buffer) +var Transform = __webpack_require__(6168) +var inherits = __webpack_require__(6698) + +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._mode = mode +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} + +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} + +module.exports = StreamCipher + + +/***/ }), + +/***/ 125: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var DES = __webpack_require__(4050) +var aes = __webpack_require__(1241) +var aesModes = __webpack_require__(530) +var desModes = __webpack_require__(2438) +var ebtk = __webpack_require__(8078) + +function createCipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) +} + +function createDecipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createDecipheriv(suite, keys.key, keys.iv) +} + +function createCipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createCipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }) + + throw new TypeError('invalid suite type') +} + +function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) + + throw new TypeError('invalid suite type') +} + +function getCiphers () { + return Object.keys(desModes).concat(aes.getCiphers()) +} + +exports.createCipher = exports.Cipher = createCipher +exports.createCipheriv = exports.Cipheriv = createCipheriv +exports.createDecipher = exports.Decipher = createDecipher +exports.createDecipheriv = exports.Decipheriv = createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + + +/***/ }), + +/***/ 4050: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var CipherBase = __webpack_require__(6168) +var des = __webpack_require__(9560) +var inherits = __webpack_require__(6698) +var Buffer = (__webpack_require__(2861).Buffer) + +var modes = { + 'des-ede3-cbc': des.CBC.instantiate(des.EDE), + 'des-ede3': des.EDE, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES +} +modes.des = modes['des-cbc'] +modes.des3 = modes['des-ede3-cbc'] +module.exports = DES +inherits(DES, CipherBase) +function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (!Buffer.isBuffer(key)) { + key = Buffer.from(key) + } + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + if (!Buffer.isBuffer(iv)) { + iv = Buffer.from(iv) + } + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) +} +DES.prototype._update = function (data) { + return Buffer.from(this._des.update(data)) +} +DES.prototype._final = function () { + return Buffer.from(this._des.final()) +} + + +/***/ }), + +/***/ 2438: +/***/ ((__unused_webpack_module, exports) => { + +exports["des-ecb"] = { + key: 8, + iv: 0 +} +exports["des-cbc"] = exports.des = { + key: 8, + iv: 8 +} +exports["des-ede3-cbc"] = exports.des3 = { + key: 24, + iv: 8 +} +exports["des-ede3"] = { + key: 24, + iv: 0 +} +exports["des-ede-cbc"] = { + key: 16, + iv: 8 +} +exports["des-ede"] = { + key: 16, + iv: 0 +} + + +/***/ }), + +/***/ 7332: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var BN = __webpack_require__(9404) +var randomBytes = __webpack_require__(3209) + +function blind (priv) { + var r = getr(priv) + var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed() + return { blinder: blinder, unblinder: r.invm(priv.modulus) } +} + +function getr (priv) { + var len = priv.modulus.byteLength() + var r + do { + r = new BN(randomBytes(len)) + } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) + return r +} + +function crt (msg, priv) { + var blinds = blind(priv) + var len = priv.modulus.byteLength() + var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus) + var c1 = blinded.toRed(BN.mont(priv.prime1)) + var c2 = blinded.toRed(BN.mont(priv.prime2)) + var qinv = priv.coefficient + var p = priv.prime1 + var q = priv.prime2 + var m1 = c1.redPow(priv.exponent1).fromRed() + var m2 = c2.redPow(priv.exponent2).fromRed() + var h = m1.isub(m2).imul(qinv).umod(p).imul(q) + return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len) +} +crt.getr = getr + +module.exports = crt + + +/***/ }), + +/***/ 5715: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +module.exports = __webpack_require__(2951); + + +/***/ }), + +/***/ 20: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var Buffer = (__webpack_require__(2861).Buffer); +var createHash = __webpack_require__(7108); +var stream = __webpack_require__(6737); +var inherits = __webpack_require__(6698); +var sign = __webpack_require__(5359); +var verify = __webpack_require__(4847); + +var algorithms = __webpack_require__(2951); +Object.keys(algorithms).forEach(function (key) { + algorithms[key].id = Buffer.from(algorithms[key].id, 'hex'); + algorithms[key.toLowerCase()] = algorithms[key]; +}); + +function Sign(algorithm) { + stream.Writable.call(this); + + var data = algorithms[algorithm]; + if (!data) { throw new Error('Unknown message digest'); } + + this._hashType = data.hash; + this._hash = createHash(data.hash); + this._tag = data.id; + this._signType = data.sign; +} +inherits(Sign, stream.Writable); + +Sign.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; + +Sign.prototype.update = function update(data, enc) { + this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data); + + return this; +}; + +Sign.prototype.sign = function signMethod(key, enc) { + this.end(); + var hash = this._hash.digest(); + var sig = sign(hash, key, this._hashType, this._signType, this._tag); + + return enc ? sig.toString(enc) : sig; +}; + +function Verify(algorithm) { + stream.Writable.call(this); + + var data = algorithms[algorithm]; + if (!data) { throw new Error('Unknown message digest'); } + + this._hash = createHash(data.hash); + this._tag = data.id; + this._signType = data.sign; +} +inherits(Verify, stream.Writable); + +Verify.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; + +Verify.prototype.update = function update(data, enc) { + this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data); + + return this; +}; + +Verify.prototype.verify = function verifyMethod(key, sig, enc) { + var sigBuffer = typeof sig === 'string' ? Buffer.from(sig, enc) : sig; + + this.end(); + var hash = this._hash.digest(); + return verify(sigBuffer, hash, key, this._signType, this._tag); +}; + +function createSign(algorithm) { + return new Sign(algorithm); +} + +function createVerify(algorithm) { + return new Verify(algorithm); +} + +module.exports = { + Sign: createSign, + Verify: createVerify, + createSign: createSign, + createVerify: createVerify +}; + + +/***/ }), + +/***/ 5359: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var Buffer = (__webpack_require__(2861).Buffer); +var createHmac = __webpack_require__(3507); +var crt = __webpack_require__(7332); +var EC = (__webpack_require__(6729).ec); +var BN = __webpack_require__(9404); +var parseKeys = __webpack_require__(8170); +var curves = __webpack_require__(4589); + +var RSA_PKCS1_PADDING = 1; + +function sign(hash, key, hashType, signType, tag) { + var priv = parseKeys(key); + if (priv.curve) { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); } + return ecSign(hash, priv); + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') { throw new Error('wrong private key type'); } + return dsaSign(hash, priv, hashType); + } + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); } + if (key.padding !== undefined && key.padding !== RSA_PKCS1_PADDING) { throw new Error('illegal or unsupported padding mode'); } + + hash = Buffer.concat([tag, hash]); + var len = priv.modulus.byteLength(); + var pad = [0, 1]; + while (hash.length + pad.length + 1 < len) { pad.push(0xff); } + pad.push(0x00); + var i = -1; + while (++i < hash.length) { pad.push(hash[i]); } + + var out = crt(pad, priv); + return out; +} + +function ecSign(hash, priv) { + var curveId = curves[priv.curve.join('.')]; + if (!curveId) { throw new Error('unknown curve ' + priv.curve.join('.')); } + + var curve = new EC(curveId); + var key = curve.keyFromPrivate(priv.privateKey); + var out = key.sign(hash); + + return Buffer.from(out.toDER()); +} + +function dsaSign(hash, priv, algo) { + var x = priv.params.priv_key; + var p = priv.params.p; + var q = priv.params.q; + var g = priv.params.g; + var r = new BN(0); + var k; + var H = bits2int(hash, q).mod(q); + var s = false; + var kv = getKey(x, q, hash, algo); + while (s === false) { + k = makeKey(q, kv, algo); + r = makeR(g, k, p, q); + s = k.invm(q).imul(H.add(x.mul(r))).mod(q); + if (s.cmpn(0) === 0) { + s = false; + r = new BN(0); + } + } + return toDER(r, s); +} + +function toDER(r, s) { + r = r.toArray(); + s = s.toArray(); + + // Pad values + if (r[0] & 0x80) { r = [0].concat(r); } + if (s[0] & 0x80) { s = [0].concat(s); } + + var total = r.length + s.length + 4; + var res = [ + 0x30, total, 0x02, r.length + ]; + res = res.concat(r, [0x02, s.length], s); + return Buffer.from(res); +} + +function getKey(x, q, hash, algo) { + x = Buffer.from(x.toArray()); + if (x.length < q.byteLength()) { + var zeros = Buffer.alloc(q.byteLength() - x.length); + x = Buffer.concat([zeros, x]); + } + var hlen = hash.length; + var hbits = bits2octets(hash, q); + var v = Buffer.alloc(hlen); + v.fill(1); + var k = Buffer.alloc(hlen); + k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + return { k: k, v: v }; +} + +function bits2int(obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { bits.ishrn(shift); } + return bits; +} + +function bits2octets(bits, q) { + bits = bits2int(bits, q); + bits = bits.mod(q); + var out = Buffer.from(bits.toArray()); + if (out.length < q.byteLength()) { + var zeros = Buffer.alloc(q.byteLength() - out.length); + out = Buffer.concat([zeros, out]); + } + return out; +} + +function makeKey(q, kv, algo) { + var t; + var k; + + do { + t = Buffer.alloc(0); + + while (t.length * 8 < q.bitLength()) { + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + t = Buffer.concat([t, kv.v]); + } + + k = bits2int(t, q); + kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest(); + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + } while (k.cmp(q) !== -1); + + return k; +} + +function makeR(g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); +} + +module.exports = sign; +module.exports.getKey = getKey; +module.exports.makeKey = makeKey; + + +/***/ }), + +/***/ 4847: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var Buffer = (__webpack_require__(2861).Buffer); +var BN = __webpack_require__(9404); +var EC = (__webpack_require__(6729).ec); +var parseKeys = __webpack_require__(8170); +var curves = __webpack_require__(4589); + +function verify(sig, hash, key, signType, tag) { + var pub = parseKeys(key); + if (pub.type === 'ec') { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); } + return ecVerify(sig, hash, pub); + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') { throw new Error('wrong public key type'); } + return dsaVerify(sig, hash, pub); + } + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); } + + hash = Buffer.concat([tag, hash]); + var len = pub.modulus.byteLength(); + var pad = [1]; + var padNum = 0; + while (hash.length + pad.length + 2 < len) { + pad.push(0xff); + padNum += 1; + } + pad.push(0x00); + var i = -1; + while (++i < hash.length) { + pad.push(hash[i]); + } + pad = Buffer.from(pad); + var red = BN.mont(pub.modulus); + sig = new BN(sig).toRed(red); + + sig = sig.redPow(new BN(pub.publicExponent)); + sig = Buffer.from(sig.fromRed().toArray()); + var out = padNum < 8 ? 1 : 0; + len = Math.min(sig.length, pad.length); + if (sig.length !== pad.length) { out = 1; } + + i = -1; + while (++i < len) { out |= sig[i] ^ pad[i]; } + return out === 0; +} + +function ecVerify(sig, hash, pub) { + var curveId = curves[pub.data.algorithm.curve.join('.')]; + if (!curveId) { throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')); } + + var curve = new EC(curveId); + var pubkey = pub.data.subjectPrivateKey.data; + + return curve.verify(hash, sig, pubkey); +} + +function dsaVerify(sig, hash, pub) { + var p = pub.data.p; + var q = pub.data.q; + var g = pub.data.g; + var y = pub.data.pub_key; + var unpacked = parseKeys.signature.decode(sig, 'der'); + var s = unpacked.s; + var r = unpacked.r; + checkValue(s, q); + checkValue(r, q); + var montp = BN.mont(p); + var w = s.invm(q); + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .mod(q); + return v.cmp(r) === 0; +} + +function checkValue(b, q) { + if (b.cmpn(0) <= 0) { throw new Error('invalid sig'); } + if (b.cmp(q) >= 0) { throw new Error('invalid sig'); } +} + +module.exports = verify; + + +/***/ }), + +/***/ 2240: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 6248: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __webpack_require__(3225); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(5622)); +util.inherits = __webpack_require__(6698); +/**/ + +var Readable = __webpack_require__(206); +var Writable = __webpack_require__(7314); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), + +/***/ 5242: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; + +var Transform = __webpack_require__(1816); + +/**/ +var util = Object.create(__webpack_require__(5622)); +util.inherits = __webpack_require__(6698); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var pna = __webpack_require__(3225); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(2240); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(7007).EventEmitter); + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(5567); +/**/ + +/**/ + +var Buffer = (__webpack_require__(4116).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(5622)); +util.inherits = __webpack_require__(6698); +/**/ + +/**/ +var debugUtil = __webpack_require__(2668); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(672); +var destroyImpl = __webpack_require__(6278); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(6248); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__webpack_require__(6427)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(6248); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__webpack_require__(6427)/* .StringDecoder */ .I); + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 1816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(6248); + +/**/ +var util = Object.create(__webpack_require__(5622)); +util.inherits = __webpack_require__(6698); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), + +/***/ 7314: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +/**/ + +var pna = __webpack_require__(3225); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(5622)); +util.inherits = __webpack_require__(6698); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(4643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(5567); +/**/ + +/**/ + +var Buffer = (__webpack_require__(4116).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(6278); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(6248); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(6248); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), + +/***/ 672: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = (__webpack_require__(4116).Buffer); +var util = __webpack_require__(1638); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), + +/***/ 6278: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(3225); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } + + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), + +/***/ 5567: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(7007).EventEmitter; + + +/***/ }), + +/***/ 4116: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 6737: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(206); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(7314); +exports.Duplex = __webpack_require__(6248); +exports.Transform = __webpack_require__(1816); +exports.PassThrough = __webpack_require__(5242); + + +/***/ }), + +/***/ 6427: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = (__webpack_require__(8393).Buffer); +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.I = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 8393: +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 295: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(6763); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 8075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBind = __webpack_require__(487); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var GetIntrinsic = __webpack_require__(453); +var setFunctionLength = __webpack_require__(6897); + +var $TypeError = __webpack_require__(9675); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = __webpack_require__(655); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ 6168: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) +var Transform = (__webpack_require__(8310).Transform) +var StringDecoder = (__webpack_require__(3141)/* .StringDecoder */ .I) +var inherits = __webpack_require__(6698) + +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null +} +inherits(CipherBase, Transform) + +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out +} + +module.exports = CipherBase + + +/***/ }), + +/***/ 6763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global window, global*/ +var util = __webpack_require__(537) +var assert = __webpack_require__(4148) +function now() { return new Date().getTime() } + +var slice = Array.prototype.slice +var console +var times = {} + +if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) { + console = __webpack_require__.g.console +} else if (typeof window !== "undefined" && window.console) { + console = window.console +} else { + console = {} +} + +var functions = [ + [log, "log"], + [info, "info"], + [warn, "warn"], + [error, "error"], + [time, "time"], + [timeEnd, "timeEnd"], + [trace, "trace"], + [dir, "dir"], + [consoleAssert, "assert"] +] + +for (var i = 0; i < functions.length; i++) { + var tuple = functions[i] + var f = tuple[0] + var name = tuple[1] + + if (!console[name]) { + console[name] = f + } +} + +module.exports = console + +function log() {} + +function info() { + console.log.apply(console, arguments) +} + +function warn() { + console.log.apply(console, arguments) +} + +function error() { + console.warn.apply(console, arguments) +} + +function time(label) { + times[label] = now() +} + +function timeEnd(label) { + var time = times[label] + if (!time) { + throw new Error("No such label: " + label) + } + + delete times[label] + var duration = now() - time + console.log(label + ": " + duration + "ms") +} + +function trace() { + var err = new Error() + err.name = "Trace" + err.message = util.format.apply(null, arguments) + console.error(err.stack) +} + +function dir(object) { + console.log(util.inspect(object) + "\n") +} + +function consoleAssert(expression) { + if (!expression) { + var arr = slice.call(arguments, 1) + assert.ok(false, util.format.apply(null, arr)) + } +} + + +/***/ }), + +/***/ 5622: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(8287).Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ 1324: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var elliptic = __webpack_require__(6729) +var BN = __webpack_require__(2801) + +module.exports = function createECDH (curve) { + return new ECDH(curve) +} + +var aliases = { + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +} + +aliases.p224 = aliases.secp224r1 +aliases.p256 = aliases.secp256r1 = aliases.prime256v1 +aliases.p192 = aliases.secp192r1 = aliases.prime192v1 +aliases.p384 = aliases.secp384r1 +aliases.p521 = aliases.secp521r1 + +function ECDH (curve) { + this.curveType = aliases[curve] + if (!this.curveType) { + this.curveType = { + name: curve + } + } + this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap + this.keys = void 0 +} + +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair() + return this.getPublicKey(enc, format) +} + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8' + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc) + } + var otherPub = this.curve.keyFromPublic(other).getPublic() + var out = otherPub.mul(this.keys.getPrivate()).getX() + return formatReturnValue(out, enc, this.curveType.byteLength) +} + +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true) + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7 + } else { + key[0] = 6 + } + } + return formatReturnValue(key, enc) +} + +ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc) +} + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc) + } + this.keys._importPublic(pub) + return this +} + +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc) + } + + var _priv = new BN(priv) + _priv = _priv.toString(16) + this.keys = this.curve.genKeyPair() + this.keys._importPrivate(_priv) + return this +} + +function formatReturnValue (bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray() + } + var buf = new Buffer(bn) + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length) + zeros.fill(0) + buf = Buffer.concat([zeros, buf]) + } + if (!enc) { + return buf + } else { + return buf.toString(enc) + } +} + + +/***/ }), + +/***/ 2801: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(7965).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 7108: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(6698) +var MD5 = __webpack_require__(8276) +var RIPEMD160 = __webpack_require__(6011) +var sha = __webpack_require__(2802) +var Base = __webpack_require__(6168) + +function Hash (hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) +} + + +/***/ }), + +/***/ 320: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var MD5 = __webpack_require__(8276) + +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} + + +/***/ }), + +/***/ 3507: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(6698) +var Legacy = __webpack_require__(1800) +var Base = __webpack_require__(6168) +var Buffer = (__webpack_require__(2861).Buffer) +var md5 = __webpack_require__(320) +var RIPEMD160 = __webpack_require__(6011) + +var sha = __webpack_require__(2802) + +var ZEROS = Buffer.alloc(128) + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.update(data) +} + +Hmac.prototype._final = function () { + var h = this._hash.digest() + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() +} + +module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) +} + + +/***/ }), + +/***/ 1800: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(6698) +var Buffer = (__webpack_require__(2861).Buffer) + +var Base = __webpack_require__(6168) + +var ZEROS = Buffer.alloc(128) +var blocksize = 64 + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = alg(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = [ipad] +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.push(data) +} + +Hmac.prototype._final = function () { + var h = this._alg(Buffer.concat(this._hash)) + return this._alg(Buffer.concat([this._opad, h])) +} +module.exports = Hmac + + +/***/ }), + +/***/ 1565: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(3209) +exports.createHash = exports.Hash = __webpack_require__(7108) +exports.createHmac = exports.Hmac = __webpack_require__(3507) + +var algos = __webpack_require__(5715) +var algoKeys = Object.keys(algos) +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) +exports.getHashes = function () { + return hashes +} + +var p = __webpack_require__(8396) +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync + +var aes = __webpack_require__(125) + +exports.Cipher = aes.Cipher +exports.createCipher = aes.createCipher +exports.Cipheriv = aes.Cipheriv +exports.createCipheriv = aes.createCipheriv +exports.Decipher = aes.Decipher +exports.createDecipher = aes.createDecipher +exports.Decipheriv = aes.Decipheriv +exports.createDecipheriv = aes.createDecipheriv +exports.getCiphers = aes.getCiphers +exports.listCiphers = aes.listCiphers + +var dh = __webpack_require__(5380) + +exports.DiffieHellmanGroup = dh.DiffieHellmanGroup +exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup +exports.getDiffieHellman = dh.getDiffieHellman +exports.createDiffieHellman = dh.createDiffieHellman +exports.DiffieHellman = dh.DiffieHellman + +var sign = __webpack_require__(20) + +exports.createSign = sign.createSign +exports.Sign = sign.Sign +exports.createVerify = sign.createVerify +exports.Verify = sign.Verify + +exports.createECDH = __webpack_require__(1324) + +var publicEncrypt = __webpack_require__(7168) + +exports.publicEncrypt = publicEncrypt.publicEncrypt +exports.privateEncrypt = publicEncrypt.privateEncrypt +exports.publicDecrypt = publicEncrypt.publicDecrypt +exports.privateDecrypt = publicEncrypt.privateDecrypt + +// the least I can do is make error messages for the rest of the node.js/crypto api. +// ;[ +// 'createCredentials' +// ].forEach(function (name) { +// exports[name] = function () { +// throw new Error([ +// 'sorry, ' + name + ' is not implemented yet', +// 'we accept pull requests', +// 'https://github.com/crypto-browserify/crypto-browserify' +// ].join('\n')) +// } +// }) + +var rf = __webpack_require__(6983) + +exports.randomFill = rf.randomFill +exports.randomFillSync = rf.randomFillSync + +exports.createCredentials = function () { + throw new Error([ + 'sorry, createCredentials is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) +} + +exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + 'POINT_CONVERSION_UNCOMPRESSED': 4, + 'POINT_CONVERSION_HYBRID': 6 +} + + +/***/ }), + +/***/ 41: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); + +var gopd = __webpack_require__(5795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ 8452: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keys = __webpack_require__(1189); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var defineDataProperty = __webpack_require__(41); + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var supportsDescriptors = __webpack_require__(592)(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; + + +/***/ }), + +/***/ 9560: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.utils = __webpack_require__(7626); +exports.Cipher = __webpack_require__(2808); +exports.DES = __webpack_require__(2211); +exports.CBC = __webpack_require__(3389); +exports.EDE = __webpack_require__(5279); + + +/***/ }), + +/***/ 3389: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(3349); +var inherits = __webpack_require__(6698); + +var proto = {}; + +function CBCState(iv) { + assert.equal(iv.length, 8, 'Invalid IV length'); + + this.iv = new Array(8); + for (var i = 0; i < this.iv.length; i++) + this.iv[i] = iv[i]; +} + +function instantiate(Base) { + function CBC(options) { + Base.call(this, options); + this._cbcInit(); + } + inherits(CBC, Base); + + var keys = Object.keys(proto); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + CBC.prototype[key] = proto[key]; + } + + CBC.create = function create(options) { + return new CBC(options); + }; + + return CBC; +} + +exports.instantiate = instantiate; + +proto._cbcInit = function _cbcInit() { + var state = new CBCState(this.options.iv); + this._cbcState = state; +}; + +proto._update = function _update(inp, inOff, out, outOff) { + var state = this._cbcState; + var superProto = this.constructor.super_.prototype; + + var iv = state.iv; + if (this.type === 'encrypt') { + for (var i = 0; i < this.blockSize; i++) + iv[i] ^= inp[inOff + i]; + + superProto._update.call(this, iv, 0, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + iv[i] = out[outOff + i]; + } else { + superProto._update.call(this, inp, inOff, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + out[outOff + i] ^= iv[i]; + + for (var i = 0; i < this.blockSize; i++) + iv[i] = inp[inOff + i]; + } +}; + + +/***/ }), + +/***/ 2808: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(3349); + +function Cipher(options) { + this.options = options; + + this.type = this.options.type; + this.blockSize = 8; + this._init(); + + this.buffer = new Array(this.blockSize); + this.bufferOff = 0; + this.padding = options.padding !== false +} +module.exports = Cipher; + +Cipher.prototype._init = function _init() { + // Might be overrided +}; + +Cipher.prototype.update = function update(data) { + if (data.length === 0) + return []; + + if (this.type === 'decrypt') + return this._updateDecrypt(data); + else + return this._updateEncrypt(data); +}; + +Cipher.prototype._buffer = function _buffer(data, off) { + // Append data to buffer + var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); + for (var i = 0; i < min; i++) + this.buffer[this.bufferOff + i] = data[off + i]; + this.bufferOff += min; + + // Shift next + return min; +}; + +Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { + this._update(this.buffer, 0, out, off); + this.bufferOff = 0; + return this.blockSize; +}; + +Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = ((this.bufferOff + data.length) / this.blockSize) | 0; + var out = new Array(count * this.blockSize); + + if (this.bufferOff !== 0) { + inputOff += this._buffer(data, inputOff); + + if (this.bufferOff === this.buffer.length) + outputOff += this._flushBuffer(out, outputOff); + } + + // Write blocks + var max = data.length - ((data.length - inputOff) % this.blockSize); + for (; inputOff < max; inputOff += this.blockSize) { + this._update(data, inputOff, out, outputOff); + outputOff += this.blockSize; + } + + // Queue rest + for (; inputOff < data.length; inputOff++, this.bufferOff++) + this.buffer[this.bufferOff] = data[inputOff]; + + return out; +}; + +Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; + var out = new Array(count * this.blockSize); + + // TODO(indutny): optimize it, this is far from optimal + for (; count > 0; count--) { + inputOff += this._buffer(data, inputOff); + outputOff += this._flushBuffer(out, outputOff); + } + + // Buffer rest of the input + inputOff += this._buffer(data, inputOff); + + return out; +}; + +Cipher.prototype.final = function final(buffer) { + var first; + if (buffer) + first = this.update(buffer); + + var last; + if (this.type === 'encrypt') + last = this._finalEncrypt(); + else + last = this._finalDecrypt(); + + if (first) + return first.concat(last); + else + return last; +}; + +Cipher.prototype._pad = function _pad(buffer, off) { + if (off === 0) + return false; + + while (off < buffer.length) + buffer[off++] = 0; + + return true; +}; + +Cipher.prototype._finalEncrypt = function _finalEncrypt() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + + var out = new Array(this.blockSize); + this._update(this.buffer, 0, out, 0); + return out; +}; + +Cipher.prototype._unpad = function _unpad(buffer) { + return buffer; +}; + +Cipher.prototype._finalDecrypt = function _finalDecrypt() { + assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); + var out = new Array(this.blockSize); + this._flushBuffer(out, 0); + + return this._unpad(out); +}; + + +/***/ }), + +/***/ 2211: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(3349); +var inherits = __webpack_require__(6698); + +var utils = __webpack_require__(7626); +var Cipher = __webpack_require__(2808); + +function DESState() { + this.tmp = new Array(2); + this.keys = null; +} + +function DES(options) { + Cipher.call(this, options); + + var state = new DESState(); + this._desState = state; + + this.deriveKeys(state, options.key); +} +inherits(DES, Cipher); +module.exports = DES; + +DES.create = function create(options) { + return new DES(options); +}; + +var shiftTable = [ + 1, 1, 2, 2, 2, 2, 2, 2, + 1, 2, 2, 2, 2, 2, 2, 1 +]; + +DES.prototype.deriveKeys = function deriveKeys(state, key) { + state.keys = new Array(16 * 2); + + assert.equal(key.length, this.blockSize, 'Invalid key length'); + + var kL = utils.readUInt32BE(key, 0); + var kR = utils.readUInt32BE(key, 4); + + utils.pc1(kL, kR, state.tmp, 0); + kL = state.tmp[0]; + kR = state.tmp[1]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + utils.pc2(kL, kR, state.keys, i); + } +}; + +DES.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._desState; + + var l = utils.readUInt32BE(inp, inOff); + var r = utils.readUInt32BE(inp, inOff + 4); + + // Initial Permutation + utils.ip(l, r, state.tmp, 0); + l = state.tmp[0]; + r = state.tmp[1]; + + if (this.type === 'encrypt') + this._encrypt(state, l, r, state.tmp, 0); + else + this._decrypt(state, l, r, state.tmp, 0); + + l = state.tmp[0]; + r = state.tmp[1]; + + utils.writeUInt32BE(out, l, outOff); + utils.writeUInt32BE(out, r, outOff + 4); +}; + +DES.prototype._pad = function _pad(buffer, off) { + if (this.padding === false) { + return false; + } + + var value = buffer.length - off; + for (var i = off; i < buffer.length; i++) + buffer[i] = value; + + return true; +}; + +DES.prototype._unpad = function _unpad(buffer) { + if (this.padding === false) { + return buffer; + } + + var pad = buffer[buffer.length - 1]; + for (var i = buffer.length - pad; i < buffer.length; i++) + assert.equal(buffer[i], pad); + + return buffer.slice(0, buffer.length - pad); +}; + +DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { + var l = lStart; + var r = rStart; + + // Apply f() x16 times + for (var i = 0; i < state.keys.length; i += 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(r, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = r; + r = (l ^ f) >>> 0; + l = t; + } + + // Reverse Initial Permutation + utils.rip(r, l, out, off); +}; + +DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { + var l = rStart; + var r = lStart; + + // Apply f() x16 times + for (var i = state.keys.length - 2; i >= 0; i -= 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(l, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = l; + l = (r ^ f) >>> 0; + r = t; + } + + // Reverse Initial Permutation + utils.rip(l, r, out, off); +}; + + +/***/ }), + +/***/ 5279: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(3349); +var inherits = __webpack_require__(6698); + +var Cipher = __webpack_require__(2808); +var DES = __webpack_require__(2211); + +function EDEState(type, key) { + assert.equal(key.length, 24, 'Invalid key length'); + + var k1 = key.slice(0, 8); + var k2 = key.slice(8, 16); + var k3 = key.slice(16, 24); + + if (type === 'encrypt') { + this.ciphers = [ + DES.create({ type: 'encrypt', key: k1 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } +} + +function EDE(options) { + Cipher.call(this, options); + + var state = new EDEState(this.type, this.options.key); + this._edeState = state; +} +inherits(EDE, Cipher); + +module.exports = EDE; + +EDE.create = function create(options) { + return new EDE(options); +}; + +EDE.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._edeState; + + state.ciphers[0]._update(inp, inOff, out, outOff); + state.ciphers[1]._update(out, outOff, out, outOff); + state.ciphers[2]._update(out, outOff, out, outOff); +}; + +EDE.prototype._pad = DES.prototype._pad; +EDE.prototype._unpad = DES.prototype._unpad; + + +/***/ }), + +/***/ 7626: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.readUInt32BE = function readUInt32BE(bytes, off) { + var res = (bytes[0 + off] << 24) | + (bytes[1 + off] << 16) | + (bytes[2 + off] << 8) | + bytes[3 + off]; + return res >>> 0; +}; + +exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { + bytes[0 + off] = value >>> 24; + bytes[1 + off] = (value >>> 16) & 0xff; + bytes[2 + off] = (value >>> 8) & 0xff; + bytes[3 + off] = value & 0xff; +}; + +exports.ip = function ip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.rip = function rip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 0; i < 4; i++) { + for (var j = 24; j >= 0; j -= 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.pc1 = function pc1(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + // 7, 15, 23, 31, 39, 47, 55, 63 + // 6, 14, 22, 30, 39, 47, 55, 63 + // 5, 13, 21, 29, 39, 47, 55, 63 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + + // 1, 9, 17, 25, 33, 41, 49, 57 + // 2, 10, 18, 26, 34, 42, 50, 58 + // 3, 11, 19, 27, 35, 43, 51, 59 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.r28shl = function r28shl(num, shift) { + return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); +}; + +var pc2table = [ + // inL => outL + 14, 11, 17, 4, 27, 23, 25, 0, + 13, 22, 7, 18, 5, 9, 16, 24, + 2, 20, 12, 21, 1, 8, 15, 26, + + // inR => outR + 15, 4, 25, 19, 9, 1, 26, 16, + 5, 11, 23, 8, 12, 7, 17, 0, + 22, 3, 10, 14, 6, 20, 27, 24 +]; + +exports.pc2 = function pc2(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + var len = pc2table.length >>> 1; + for (var i = 0; i < len; i++) { + outL <<= 1; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + outR <<= 1; + outR |= (inR >>> pc2table[i]) & 0x1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.expand = function expand(r, out, off) { + var outL = 0; + var outR = 0; + + outL = ((r & 1) << 5) | (r >>> 27); + for (var i = 23; i >= 15; i -= 4) { + outL <<= 6; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + outR <<= 6; + } + outR |= ((r & 0x1f) << 1) | (r >>> 31); + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +var sTable = [ + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, + + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, + + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, + + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, + + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, + + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, + + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, + + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 +]; + +exports.substitute = function substitute(inL, inR) { + var out = 0; + for (var i = 0; i < 4; i++) { + var b = (inL >>> (18 - i * 6)) & 0x3f; + var sb = sTable[i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + for (var i = 0; i < 4; i++) { + var b = (inR >>> (18 - i * 6)) & 0x3f; + var sb = sTable[4 * 0x40 + i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + return out >>> 0; +}; + +var permuteTable = [ + 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, + 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 +]; + +exports.permute = function permute(num) { + var out = 0; + for (var i = 0; i < permuteTable.length; i++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + return out >>> 0; +}; + +exports.padSplit = function padSplit(num, size, group) { + var str = num.toString(2); + while (str.length < size) + str = '0' + str; + + var out = []; + for (var i = 0; i < size; i += group) + out.push(str.slice(i, i + group)); + return out.join(' '); +}; + + +/***/ }), + +/***/ 5380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var generatePrime = __webpack_require__(4934) +var primes = __webpack_require__(3241) + +var DH = __webpack_require__(4910) + +function getDiffieHellman (mod) { + var prime = new Buffer(primes[mod].prime, 'hex') + var gen = new Buffer(primes[mod].gen, 'hex') + + return new DH(prime, gen) +} + +var ENCODINGS = { + 'binary': true, 'hex': true, 'base64': true +} + +function createDiffieHellman (prime, enc, generator, genc) { + if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { + return createDiffieHellman(prime, 'binary', enc, generator) + } + + enc = enc || 'binary' + genc = genc || 'binary' + generator = generator || new Buffer([2]) + + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc) + } + + if (typeof prime === 'number') { + return new DH(generatePrime(prime, generator), generator, true) + } + + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc) + } + + return new DH(prime, generator, true) +} + +exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman +exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman + + +/***/ }), + +/***/ 4910: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var BN = __webpack_require__(6473); +var MillerRabin = __webpack_require__(2244); +var millerRabin = new MillerRabin(); +var TWENTYFOUR = new BN(24); +var ELEVEN = new BN(11); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var primes = __webpack_require__(4934); +var randomBytes = __webpack_require__(3209); +module.exports = DH; + +function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; +} + +function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; +} + +var primeCache = {}; +function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + return primeCache[hex]; + } + var error = 0; + + if (prime.isEven() || + !primes.simpleSieve || + !primes.fermatTest(prime) || + !millerRabin.test(prime)) { + //not a prime so +1 + error += 1; + + if (gen === '02' || gen === '05') { + // we'd be able to check the generator + // it would fail so +8 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; +} + +function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } +} +Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } +}); +DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); +}; + +DH.prototype.computeSecret = function (other) { + other = new BN(other); + other = other.toRed(this._prime); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; +}; + +DH.prototype.getPublicKey = function getPublicKey(enc) { + return formatReturnValue(this._pub, enc); +}; + +DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return formatReturnValue(this._priv, enc); +}; + +DH.prototype.getPrime = function (enc) { + return formatReturnValue(this.__prime, enc); +}; + +DH.prototype.getGenerator = function (enc) { + return formatReturnValue(this._gen, enc); +}; + +DH.prototype.setGenerator = function (gen, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; +}; + +function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} + + +/***/ }), + +/***/ 4934: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var randomBytes = __webpack_require__(3209); +module.exports = findPrime; +findPrime.simpleSieve = simpleSieve; +findPrime.fermatTest = fermatTest; +var BN = __webpack_require__(6473); +var TWENTYFOUR = new BN(24); +var MillerRabin = __webpack_require__(2244); +var millerRabin = new MillerRabin(); +var ONE = new BN(1); +var TWO = new BN(2); +var FIVE = new BN(5); +var SIXTEEN = new BN(16); +var EIGHT = new BN(8); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var ELEVEN = new BN(11); +var FOUR = new BN(4); +var TWELVE = new BN(12); +var primes = null; + +function _getPrimes() { + if (primes !== null) + return primes; + + var limit = 0x100000; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + + if (i !== j && res[j] <= sqrt) + continue; + + res[i++] = k; + } + primes = res; + return res; +} + +function simpleSieve(p) { + var primes = _getPrimes(); + + for (var i = 0; i < primes.length; i++) + if (p.modn(primes[i]) === 0) { + if (p.cmpn(primes[i]) === 0) { + return true; + } else { + return false; + } + } + + return true; +} + +function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; +} + +function findPrime(bits, gen) { + if (bits < 16) { + // this is what openssl does + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + +} + + +/***/ }), + +/***/ 6473: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(6089).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 6729: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var elliptic = exports; + +elliptic.version = (__webpack_require__(1636)/* .version */ .rE); +elliptic.utils = __webpack_require__(7011); +elliptic.rand = __webpack_require__(5037); +elliptic.curve = __webpack_require__(894); +elliptic.curves = __webpack_require__(480); + +// Protocols +elliptic.ec = __webpack_require__(7447); +elliptic.eddsa = __webpack_require__(8650); + + +/***/ }), + +/***/ 6677: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); +var utils = __webpack_require__(7011); +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + + this._bitLength = this.n ? this.n.bitLength() : 0; + + // Generalized Greg Maxwell's trick + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + var j; + var nafW; + for (j = 0; j < naf.length; j += doubles.step) { + nafW = 0; + for (var l = j + doubles.step - 1; l >= j; l--) + nafW = (nafW << 1) + naf[l]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (j = 0; j < repr.length; j++) { + nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w, this._bitLength); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var l = 0; i >= 0 && naf[i] === 0; i--) + l++; + if (i >= 0) + l++; + acc = acc.dblp(l); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + var i; + var j; + var p; + for (i = 0; i < len; i++) { + p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); + naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3, /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (j = 0; j < len; j++) { + var z = tmp[j]; + p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null, + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles, + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res, + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + + +/***/ }), + +/***/ 1298: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7011); +var BN = __webpack_require__(8490); +var inherits = __webpack_require__(6698); +var Base = __webpack_require__(6677); + +var assert = utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + var e; + var h; + var j; + if (this.curve.twisted) { + // E = a * C + e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + h = this.z.redSqr(); + // J = F - 2 * H + j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + e = c.redAdd(d); + // H = (c * Z1)^2 + h = this.curve._mulC(this.z).redSqr(); + // J = E - 2 * H + j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + + +/***/ }), + +/***/ 894: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curve = exports; + +curve.base = __webpack_require__(6677); +curve.short = __webpack_require__(9188); +curve.mont = __webpack_require__(370); +curve.edwards = __webpack_require__(1298); + + +/***/ }), + +/***/ 370: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); +var inherits = __webpack_require__(6698); +var Base = __webpack_require__(6677); + +var utils = __webpack_require__(7011); + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + + +/***/ }), + +/***/ 9188: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7011); +var BN = __webpack_require__(8490); +var inherits = __webpack_require__(6698); +var Base = __webpack_require__(6677); + +var assert = utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis, + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; + }; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul), + }, + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1), + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1), + }, + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)), + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)), + }, + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + if (this.isInfinity()) + return this; + else if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate), + }, + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + + +/***/ }), + +/***/ 480: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var curves = exports; + +var hash = __webpack_require__(7952); +var curve = __webpack_require__(894); +var utils = __webpack_require__(7011); + +var assert = utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve.short(options); + else if (options.type === 'edwards') + this.curve = new curve.edwards(options); + else + this.curve = new curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve, + }); + return curve; + }, + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811', + ], +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34', + ], +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5', + ], +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f', + ], +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650', + ], +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9', + ], +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658', + ], +}); + +var pre; +try { + pre = __webpack_require__(4011); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3', + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15', + }, + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre, + ], +}); + + +/***/ }), + +/***/ 7447: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); +var HmacDRBG = __webpack_require__(2723); +var utils = __webpack_require__(7011); +var curves = __webpack_require__(480); +var rand = __webpack_require__(5037); +var assert = utils.assert; + +var KeyPair = __webpack_require__(1200); +var Signature = __webpack_require__(8545); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(Object.prototype.hasOwnProperty.call(curves, options), + 'Unknown curve ' + options); + + options = curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray(), + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + for (;;) { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } +}; + +EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + var p; + + if (!this.curve._maxwellTrick) { + p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; + + +/***/ }), + +/***/ 1200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); +var utils = __webpack_require__(7011); +var assert = utils.assert; + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc, + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc, + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + + +/***/ }), + +/***/ 8545: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); + +var utils = __webpack_require__(7011); +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + + // Indefinite length or overflow + if (octetLen === 0 || octetLen > 4) { + return false; + } + + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; + } + + // Leading zeroes + if (val <= 0x7f) { + return false; + } + + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if (len === false) { + return false; + } + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + if (rlen === false) { + return false; + } + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (slen === false) { + return false; + } + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0) { + if (r[1] & 0x80) { + r = r.slice(1); + } else { + // Leading zeroes + return false; + } + } + if (s[0] === 0) { + if (s[1] & 0x80) { + s = s.slice(1); + } else { + // Leading zeroes + return false; + } + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 8650: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(7952); +var curves = __webpack_require__(480); +var utils = __webpack_require__(7011); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = __webpack_require__(6661); +var Signature = __webpack_require__(220); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + curve = curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; + + +/***/ }), + +/***/ 6661: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7011); +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; + + +/***/ }), + +/***/ 220: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var BN = __webpack_require__(8490); +var utils = __webpack_require__(7011); +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; + + +/***/ }), + +/***/ 4011: +/***/ ((module) => { + +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821', + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf', + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695', + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9', + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36', + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f', + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999', + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09', + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d', + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088', + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d', + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8', + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a', + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453', + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160', + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0', + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6', + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589', + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17', + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda', + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd', + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2', + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6', + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f', + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01', + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3', + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f', + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7', + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78', + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1', + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150', + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82', + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc', + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b', + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51', + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45', + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120', + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84', + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d', + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d', + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8', + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8', + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac', + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f', + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962', + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907', + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec', + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d', + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414', + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd', + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0', + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811', + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1', + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c', + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73', + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd', + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405', + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589', + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e', + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27', + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1', + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482', + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945', + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573', + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82', + ], + ], + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672', + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6', + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da', + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37', + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b', + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81', + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58', + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77', + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a', + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c', + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67', + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402', + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55', + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482', + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82', + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396', + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49', + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf', + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a', + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7', + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933', + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a', + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6', + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37', + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e', + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6', + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476', + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40', + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61', + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683', + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5', + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b', + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417', + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868', + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a', + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6', + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996', + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e', + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d', + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2', + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e', + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437', + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311', + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4', + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575', + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d', + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d', + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629', + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06', + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374', + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee', + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1', + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b', + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661', + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6', + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e', + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d', + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc', + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4', + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c', + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b', + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913', + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154', + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865', + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc', + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224', + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e', + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6', + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511', + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b', + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2', + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c', + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3', + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d', + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700', + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4', + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196', + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4', + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257', + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13', + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096', + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38', + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f', + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448', + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a', + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4', + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437', + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7', + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d', + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a', + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54', + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77', + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517', + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10', + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125', + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e', + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1', + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2', + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423', + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8', + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758', + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375', + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d', + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec', + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0', + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c', + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4', + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f', + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649', + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826', + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5', + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87', + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b', + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc', + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c', + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f', + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a', + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46', + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f', + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03', + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08', + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8', + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373', + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3', + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8', + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1', + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9', + ], + ], + }, +}; + + +/***/ }), + +/***/ 7011: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = exports; +var BN = __webpack_require__(8490); +var minAssert = __webpack_require__(3349); +var minUtils = __webpack_require__(4367); + +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; + +// Represent num in a w-NAF form +function getNAF(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + var i; + for (i = 0; i < naf.length; i += 1) { + naf[i] = 0; + } + + var ws = 1 << (w + 1); + var k = num.clone(); + + for (i = 0; i < naf.length; i++) { + var z; + var mod = k.andln(ws - 1); + if (k.isOdd()) { + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + + naf[i] = z; + k.iushrn(1); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + var m8; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + + + +/***/ }), + +/***/ 8490: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(9368).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 655: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ 1237: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ 9383: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 9290: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ 9538: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ 8068: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ 9675: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ 5345: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ 7007: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(6763); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), + +/***/ 8078: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) +var MD5 = __webpack_require__(8276) + +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') + } + + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) + + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() + + var used = 0 + + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } + + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length + } + } + + tmp.fill(0) + return { key: key, iv: iv } +} + +module.exports = EVP_BytesToKey + + +/***/ }), + +/***/ 2682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isCallable = __webpack_require__(9600); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; + + +/***/ }), + +/***/ 9353: +/***/ ((module) => { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ 6743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(9353); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var undefined; + +var $Error = __webpack_require__(9383); +var $EvalError = __webpack_require__(1237); +var $RangeError = __webpack_require__(9290); +var $ReferenceError = __webpack_require__(9538); +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); +var $URIError = __webpack_require__(5345); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(4039)(); +var hasProto = __webpack_require__(24)(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(6743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ 5795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ 592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ 24: +/***/ ((module) => { + +"use strict"; + + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; + + +/***/ }), + +/***/ 4039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(1333); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ 1333: +/***/ ((module) => { + +"use strict"; + + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ 9092: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasSymbols = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; + + +/***/ }), + +/***/ 7952: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var hash = exports; + +hash.utils = __webpack_require__(7426); +hash.common = __webpack_require__(6166); +hash.sha = __webpack_require__(6229); +hash.ripemd = __webpack_require__(6784); +hash.hmac = __webpack_require__(8948); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; + + +/***/ }), + +/***/ 6166: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var assert = __webpack_require__(3349); + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; + + +/***/ }), + +/***/ 8948: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var assert = __webpack_require__(3349); + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + + +/***/ }), + +/***/ 6784: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var common = __webpack_require__(6166); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + + +/***/ }), + +/***/ 6229: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.sha1 = __webpack_require__(3917); +exports.sha224 = __webpack_require__(7714); +exports.sha256 = __webpack_require__(2287); +exports.sha384 = __webpack_require__(1911); +exports.sha512 = __webpack_require__(7766); + + +/***/ }), + +/***/ 3917: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var common = __webpack_require__(6166); +var shaCommon = __webpack_require__(6225); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 7714: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var SHA256 = __webpack_require__(2287); + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + + + +/***/ }), + +/***/ 2287: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var common = __webpack_require__(6166); +var shaCommon = __webpack_require__(6225); +var assert = __webpack_require__(3349); + +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; + +var BlockHash = common.BlockHash; + +var sha256_K = [ + 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 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + + +/***/ }), + +/***/ 1911: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); + +var SHA512 = __webpack_require__(7766); + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + + +/***/ }), + +/***/ 7766: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var common = __webpack_require__(6166); +var assert = __webpack_require__(3349); + +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; + +var BlockHash = common.BlockHash; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + + +/***/ }), + +/***/ 6225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7426); +var rotr32 = utils.rotr32; + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +exports.ft_1 = ft_1; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +exports.ch32 = ch32; + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +exports.maj32 = maj32; + +function p32(x, y, z) { + return x ^ y ^ z; +} +exports.p32 = p32; + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} +exports.s0_256 = s0_256; + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} +exports.s1_256 = s1_256; + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} +exports.g0_256 = g0_256; + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} +exports.g1_256 = g1_256; + + +/***/ }), + +/***/ 7426: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var assert = __webpack_require__(3349); +var inherits = __webpack_require__(6698); + +exports.inherits = inherits; + +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; +} + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + // Inspired by stringToUtf8ByteArray() in closure-library by Google + // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 + // Apache License 2.0 + // https://github.com/google/closure-library/blob/master/LICENSE + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = (c >> 6) | 192; + res[p++] = (c & 63) | 128; + } else if (isSurrogatePair(msg, i)) { + c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); + res[p++] = (c >> 18) | 240; + res[p++] = ((c >> 12) & 63) | 128; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } else { + res[p++] = (c >> 12) | 224; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +exports.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +exports.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +exports.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +exports.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +exports.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +exports.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +exports.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +exports.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +exports.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +exports.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +exports.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +exports.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +exports.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +exports.sum32_5 = sum32_5; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +} +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +} +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.shr64_lo = shr64_lo; + + +/***/ }), + +/***/ 9957: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(6743); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ 2723: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hash = __webpack_require__(7952); +var utils = __webpack_require__(4367); +var assert = __webpack_require__(3349); + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils.toArray(options.pers, options.persEnc || 'hex'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); +}; + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 7244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasToStringTag = __webpack_require__(9092)(); +var callBound = __webpack_require__(8075); + +var $toString = callBound('Object.prototype.toString'); + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + $toString(value) !== '[object Array]' && + $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + + +/***/ }), + +/***/ 9600: +/***/ ((module) => { + +"use strict"; + + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; + + +/***/ }), + +/***/ 8184: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = __webpack_require__(9092)(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; + + +/***/ }), + +/***/ 3003: +/***/ ((module) => { + +"use strict"; + + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function isNaN(value) { + return value !== value; +}; + + +/***/ }), + +/***/ 4133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var callBind = __webpack_require__(487); +var define = __webpack_require__(8452); + +var implementation = __webpack_require__(3003); +var getPolyfill = __webpack_require__(6642); +var shim = __webpack_require__(2464); + +var polyfill = callBind(getPolyfill(), Number); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 6642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(3003); + +module.exports = function getPolyfill() { + if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { + return Number.isNaN; + } + return implementation; +}; + + +/***/ }), + +/***/ 2464: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(8452); +var getPolyfill = __webpack_require__(6642); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function shimNumberIsNaN() { + var polyfill = getPolyfill(); + define(Number, { isNaN: polyfill }, { + isNaN: function testIsNaN() { + return Number.isNaN !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 5680: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var whichTypedArray = __webpack_require__(5767); + +/** @type {import('.')} */ +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; + + +/***/ }), + +/***/ 1176: +/***/ ((module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(5606); +var __WEBPACK_AMD_DEFINE_RESULT__;/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ +/*jslint bitwise: true */ +(function () { + 'use strict'; + + var INPUT_ERROR = 'input is invalid type'; + var FINALIZE_ERROR = 'finalize already called'; + var WINDOW = typeof window === 'object'; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === 'object'; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = __webpack_require__.g; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && "object" === 'object' && module.exports; + var AMD = true && __webpack_require__.amdO; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var CSHAKE_PADDING = [4, 1024, 262144, 67108864]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest']; + var CSHAKE_BYTEPAD = { + '128': 168, + '256': 136 + }; + + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + } + + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function (obj) { + return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createCshakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits, n, s) { + return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); + }; + }; + + var createKmacOutputMethod = function (bits, padding, outputType) { + return function (key, message, outputBits, s) { + return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); + }; + }; + + var createOutputMethods = function (method, createMethod, bits, padding) { + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createMethod(bits, padding, type); + } + return method; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits, padding); + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits, padding); + }; + + var createCshakeMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createCshakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits, n, s) { + if (!n && !s) { + return methods['shake' + bits].create(outputBits); + } else { + return new Keccak(bits, padding, outputBits).bytepad([n, s], w); + } + }; + method.update = function (message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits, padding); + }; + + var createKmacMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createKmacOutputMethod(bits, padding, 'hex'); + method.create = function (key, outputBits, s) { + return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w); + }; + method.update = function (key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits, padding); + }; + + var algorithms = [ + { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, + { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod }, + { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod }, + { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod }, + { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod } + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name + '_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== 'sha3') { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== 'string') { + if (type === 'object') { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.encode = function (x, right) { + var o = x & 255, n = 1; + var bytes = [o]; + x = x >> 8; + o = x & 255; + while (o > 0) { + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + + Keccak.prototype.encodeString = function (str) { + var notString, type = typeof str; + if (type !== 'string') { + if (type === 'object') { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for (var i = 0; i < str.length; ++i) { + var code = str.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code < 0xd800 || code >= 0xe000) { + bytes += 3; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + + Keccak.prototype.bytepad = function (strs, w) { + var bytes = this.encode(w); + for (var i = 0; i < strs.length; ++i) { + bytes += this.encodeString(strs[i]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + + Keccak.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + function Kmac(bits, padding, outputBits) { + Keccak.call(this, bits, padding, outputBits); + } + + Kmac.prototype = new Keccak(); + + Kmac.prototype.finalize = function () { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + if (AMD) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return methods; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } + } +})(); + + +/***/ }), + +/***/ 8276: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var inherits = __webpack_require__(6698) +var HashBase = __webpack_require__(3726) +var Buffer = (__webpack_require__(2861).Buffer) + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 + + +/***/ }), + +/***/ 3726: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(2861).Buffer) +var Transform = (__webpack_require__(8399).Transform) +var inherits = __webpack_require__(6698) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + + +/***/ }), + +/***/ 2244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var bn = __webpack_require__(1158); +var brorand = __webpack_require__(5037); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._randbelow = function _randbelow(n) { + var len = n.bitLength(); + var min_bytes = Math.ceil(len / 8); + + // Generage random bytes until a number less than n is found. + // This ensures that 0..n-1 have an equal probability of being selected. + do + var a = new bn(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + + return a; +}; + +MillerRabin.prototype._randrange = function _randrange(start, stop) { + // Generate a random number greater than or equal to start and less than stop. + var size = stop.sub(start); + return start.add(this._randbelow(size)); +}; + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return false; +}; + + +/***/ }), + +/***/ 1158: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(4688).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 3349: +/***/ ((module) => { + +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + + +/***/ }), + +/***/ 4367: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + + +/***/ }), + +/***/ 6889: +/***/ ((module) => { + +module.exports = assert + +class AssertionError extends Error {} +AssertionError.prototype.name = 'AssertionError' + +/** + * Minimal assert function + * @param {any} t Value to check if falsy + * @param {string=} m Optional assertion error message + * @throws {AssertionError} + */ +function assert (t, m) { + if (!t) { + var err = new AssertionError(m) + if (Error.captureStackTrace) Error.captureStackTrace(err, assert) + throw err + } +} + + +/***/ }), + +/***/ 9211: +/***/ ((module) => { + +"use strict"; + + +var numberIsNaN = function (value) { + return value !== value; +}; + +module.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; +}; + + + +/***/ }), + +/***/ 7653: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(8452); +var callBind = __webpack_require__(487); + +var implementation = __webpack_require__(9211); +var getPolyfill = __webpack_require__(9394); +var shim = __webpack_require__(6576); + +var polyfill = callBind(getPolyfill(), Object); + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 9394: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(9211); + +module.exports = function getPolyfill() { + return typeof Object.is === 'function' ? Object.is : implementation; +}; + + +/***/ }), + +/***/ 6576: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var getPolyfill = __webpack_require__(9394); +var define = __webpack_require__(8452); + +module.exports = function shimObjectIs() { + var polyfill = getPolyfill(); + define(Object, { is: polyfill }, { + is: function testObjectIs() { + return Object.is !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 8875: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = __webpack_require__(1093); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; + + +/***/ }), + +/***/ 1189: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var slice = Array.prototype.slice; +var isArgs = __webpack_require__(1093); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(8875); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; + + +/***/ }), + +/***/ 1093: +/***/ ((module) => { + +"use strict"; + + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + + +/***/ }), + +/***/ 8403: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = __webpack_require__(1189); +var hasSymbols = __webpack_require__(1333)(); +var callBound = __webpack_require__(8075); +var toObject = Object; +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = toObject(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = toObject(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; + + +/***/ }), + +/***/ 1514: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(8403); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; + + +/***/ }), + +/***/ 1072: +/***/ ((__unused_webpack_module, exports) => { + +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +exports.homedir = function () { + return '/' +}; + + +/***/ }), + +/***/ 1137: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + + + +var asn1 = __webpack_require__(7568); + +exports.certificate = __webpack_require__(6413); + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('modulus')['int'](), + this.key('publicExponent')['int'](), + this.key('privateExponent')['int'](), + this.key('prime1')['int'](), + this.key('prime2')['int'](), + this.key('exponent1')['int'](), + this.key('exponent2')['int'](), + this.key('coefficient')['int']() + ); +}); +exports.RSAPrivateKey = RSAPrivateKey; + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus')['int'](), + this.key('publicExponent')['int']() + ); +}); +exports.RSAPublicKey = RSAPublicKey; + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int']() + ).optional() + ); +}); + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +exports.PublicKey = PublicKey; + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.PrivateKey = PrivateKeyInfo; +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters')['int']() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ); +}); + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int'](), + this.key('pub_key')['int'](), + this.key('priv_key')['int']() + ); +}); +exports.DSAPrivateKey = DSAPrivateKey; + +exports.DSAparam = asn1.define('DSAparam', function () { + this['int'](); +}); + +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }); +}); + +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ); +}); +exports.ECPrivateKey = ECPrivateKey; + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r')['int'](), + this.key('s')['int']() + ); +}); + + +/***/ }), + +/***/ 6413: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js +// thanks to @Rantanen + + + +var asn = __webpack_require__(7568); + +var Time = asn.define('Time', function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }); +}); + +var AttributeTypeValue = asn.define('AttributeTypeValue', function () { + this.seq().obj( + this.key('type').objid(), + this.key('value').any() + ); +}); + +var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional(), + this.key('curve').objid().optional() + ); +}); + +var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); + +var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { + this.setof(AttributeTypeValue); +}); + +var RDNSequence = asn.define('RDNSequence', function () { + this.seqof(RelativeDistinguishedName); +}); + +var Name = asn.define('Name', function () { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); +}); + +var Validity = asn.define('Validity', function () { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); + +var Extension = asn.define('Extension', function () { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ); +}); + +var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0)['int']().optional(), + this.key('serialNumber')['int'](), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ); +}); + +var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ); +}); + +module.exports = X509Certificate; + + +/***/ }), + +/***/ 4101: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m; +var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m; +var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m; +var evp = __webpack_require__(8078); +var ciphers = __webpack_require__(1241); +var Buffer = (__webpack_require__(2861).Buffer); +module.exports = function (okey, password) { + var key = okey.toString(); + var match = key.match(findProc); + var decrypted; + if (!match) { + var match2 = key.match(fullRegex); + decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64'); + } else { + var suite = 'aes' + match[1]; + var iv = Buffer.from(match[2], 'hex'); + var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64'); + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key; + var out = []; + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv); + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + decrypted = Buffer.concat(out); + } + var tag = key.match(startRegex)[1]; + return { + tag: tag, + data: decrypted + }; +}; + + +/***/ }), + +/***/ 8170: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var asn1 = __webpack_require__(1137); +var aesid = __webpack_require__(5579); +var fixProc = __webpack_require__(4101); +var ciphers = __webpack_require__(1241); +var compat = __webpack_require__(8396); +var Buffer = (__webpack_require__(2861).Buffer); + +function decrypt(data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt; + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10); + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]; + var iv = data.algorithm.decrypt.cipher.iv; + var cipherText = data.subjectPrivateKey; + var keylen = parseInt(algo.split('-')[1], 10) / 8; + var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1'); + var cipher = ciphers.createDecipheriv(algo, key, iv); + var out = []; + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + return Buffer.concat(out); +} + +function parseKeys(buffer) { + var password; + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase; + buffer = buffer.key; + } + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer); + } + + var stripped = fixProc(buffer, password); + + var type = stripped.tag; + var data = stripped.data; + var subtype, ndata; + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo; + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der'); + } + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der'); + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey; + return { + type: 'ec', + data: ndata + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der'); + return { + type: 'dsa', + data: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der'); + data = decrypt(data, password); + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der'); + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der'); + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der'); + return { + type: 'dsa', + params: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der'); + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der'); + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + }; + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der'); + return { + curve: data.parameters.value, + privateKey: data.privateKey + }; + default: throw new Error('unknown key type ' + type); + } +} +parseKeys.signature = asn1.signature; + +module.exports = parseKeys; + + +/***/ }), + +/***/ 8396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.pbkdf2 = __webpack_require__(3832) +exports.pbkdf2Sync = __webpack_require__(1352) + + +/***/ }), + +/***/ 3832: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) + +var checkParameters = __webpack_require__(4196) +var defaultEncoding = __webpack_require__(2455) +var sync = __webpack_require__(1352) +var toBuffer = __webpack_require__(3382) + +var ZERO_BUF +var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle +var toBrowser = { + sha: 'SHA-1', + 'sha-1': 'SHA-1', + sha1: 'SHA-1', + sha256: 'SHA-256', + 'sha-256': 'SHA-256', + sha384: 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + sha512: 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom +} +var nextTick +function getNextTick () { + if (nextTick) { + return nextTick + } + if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) { + nextTick = __webpack_require__.g.process.nextTick + } else if (__webpack_require__.g.queueMicrotask) { + nextTick = __webpack_require__.g.queueMicrotask + } else if (__webpack_require__.g.setImmediate) { + nextTick = __webpack_require__.g.setImmediate + } else { + nextTick = __webpack_require__.g.setTimeout + } + return nextTick +} +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) +} + +function resolvePromise (promise, callback) { + promise.then(function (out) { + getNextTick()(function () { + callback(null, out) + }) + }, function (e) { + getNextTick()(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] + + if (!algo || typeof __webpack_require__.g.Promise !== 'function') { + getNextTick()(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + return + } + + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + + return sync(password, salt, iterations, keylen, digest) + }), callback) +} + + +/***/ }), + +/***/ 2455: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(5606); +var defaultEncoding +/* istanbul ignore next */ +if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { + defaultEncoding = 'utf-8' +} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} else { + defaultEncoding = 'utf-8' +} +module.exports = defaultEncoding + + +/***/ }), + +/***/ 4196: +/***/ ((module) => { + +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + + +/***/ }), + +/***/ 1352: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var md5 = __webpack_require__(320) +var RIPEMD160 = __webpack_require__(6011) +var sha = __webpack_require__(2802) +var Buffer = (__webpack_require__(2861).Buffer) + +var checkParameters = __webpack_require__(4196) +var defaultEncoding = __webpack_require__(2455) +var toBuffer = __webpack_require__(3382) + +var ZEROS = Buffer.alloc(128) +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} + +function Hmac (alg, key, saltLen) { + var hash = getDigest(alg) + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + if (key.length > blocksize) { + key = hash(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) + ipad.copy(ipad1, 0, 0, blocksize) + this.ipad1 = ipad1 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + this.hash = hash + this.size = sizes[alg] +} + +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize) + var h = this.hash(ipad) + h.copy(this.opad, this.blocksize) + return this.hash(this.opad) +} + +function getDigest (alg) { + function shaFunc (data) { + return sha(alg).update(data).digest() + } + function rmd160Func (data) { + return new RIPEMD160().update(data).digest() + } + + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func + if (alg === 'md5') return md5 + return shaFunc +} + +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + + digest = digest || 'sha1' + + var hmac = new Hmac(digest, password, salt.length) + + var DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var T = hmac.run(block1, hmac.ipad1) + var U = T + + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2) + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + T.copy(DK, destPos) + destPos += hLen + } + + return DK +} + +module.exports = pbkdf2 + + +/***/ }), + +/***/ 3382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) + +module.exports = function (thing, encoding, name) { + if (Buffer.isBuffer(thing)) { + return thing + } else if (typeof thing === 'string') { + return Buffer.from(thing, encoding) + } else if (ArrayBuffer.isView(thing)) { + return Buffer.from(thing.buffer) + } else { + throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') + } +} + + +/***/ }), + +/***/ 6578: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = [ + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' +]; + + +/***/ }), + +/***/ 3225: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 5606: +/***/ ((module) => { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ 7168: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.publicEncrypt = __webpack_require__(8902) +exports.privateDecrypt = __webpack_require__(7362) + +exports.privateEncrypt = function privateEncrypt (key, buf) { + return exports.publicEncrypt(key, buf, true) +} + +exports.publicDecrypt = function publicDecrypt (key, buf) { + return exports.privateDecrypt(key, buf, true) +} + + +/***/ }), + +/***/ 8206: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var createHash = __webpack_require__(7108) +var Buffer = (__webpack_require__(2861).Buffer) + +module.exports = function (seed, len) { + var t = Buffer.alloc(0) + var i = 0 + var c + while (t.length < len) { + c = i2ops(i++) + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]) + } + return t.slice(0, len) +} + +function i2ops (c) { + var out = Buffer.allocUnsafe(4) + out.writeUInt32BE(c, 0) + return out +} + + +/***/ }), + +/***/ 2509: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = (__webpack_require__(1069).Buffer); + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})( false || module, this); + + +/***/ }), + +/***/ 7362: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(8170) +var mgf = __webpack_require__(8206) +var xor = __webpack_require__(2061) +var BN = __webpack_require__(2509) +var crt = __webpack_require__(7332) +var createHash = __webpack_require__(7108) +var withPublic = __webpack_require__(9247) +var Buffer = (__webpack_require__(2861).Buffer) + +module.exports = function privateDecrypt (privateKey, enc, reverse) { + var padding + if (privateKey.padding) { + padding = privateKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + + var key = parseKeys(privateKey) + var k = key.modulus.byteLength() + if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error') + } + var msg + if (reverse) { + msg = withPublic(new BN(enc), key) + } else { + msg = crt(enc, key) + } + var zBuffer = Buffer.alloc(k - msg.length) + msg = Buffer.concat([zBuffer, msg], k) + if (padding === 4) { + return oaep(key, msg) + } else if (padding === 1) { + return pkcs1(key, msg, reverse) + } else if (padding === 3) { + return msg + } else { + throw new Error('unknown padding') + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + if (msg[0] !== 0) { + throw new Error('decryption error') + } + var maskedSeed = msg.slice(1, hLen + 1) + var maskedDb = msg.slice(hLen + 1) + var seed = xor(maskedSeed, mgf(maskedDb, hLen)) + var db = xor(maskedDb, mgf(seed, k - hLen - 1)) + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error') + } + var i = hLen + while (db[i] === 0) { + i++ + } + if (db[i++] !== 1) { + throw new Error('decryption error') + } + return db.slice(i) +} + +function pkcs1 (key, msg, reverse) { + var p1 = msg.slice(0, 2) + var i = 2 + var status = 0 + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++ + break + } + } + var ps = msg.slice(2, i - 1) + + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) { + status++ + } + if (ps.length < 8) { + status++ + } + if (status) { + throw new Error('decryption error') + } + return msg.slice(i) +} +function compare (a, b) { + a = Buffer.from(a) + b = Buffer.from(b) + var dif = 0 + var len = a.length + if (a.length !== b.length) { + dif++ + len = Math.min(a.length, b.length) + } + var i = -1 + while (++i < len) { + dif += (a[i] ^ b[i]) + } + return dif +} + + +/***/ }), + +/***/ 8902: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parseKeys = __webpack_require__(8170) +var randomBytes = __webpack_require__(3209) +var createHash = __webpack_require__(7108) +var mgf = __webpack_require__(8206) +var xor = __webpack_require__(2061) +var BN = __webpack_require__(2509) +var withPublic = __webpack_require__(9247) +var crt = __webpack_require__(7332) +var Buffer = (__webpack_require__(2861).Buffer) + +module.exports = function publicEncrypt (publicKey, msg, reverse) { + var padding + if (publicKey.padding) { + padding = publicKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + var key = parseKeys(publicKey) + var paddedMsg + if (padding === 4) { + paddedMsg = oaep(key, msg) + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse) + } else if (padding === 3) { + paddedMsg = new BN(msg) + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus') + } + } else { + throw new Error('unknown padding') + } + if (reverse) { + return crt(paddedMsg, key) + } else { + return withPublic(paddedMsg, key) + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var mLen = msg.length + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + var hLen2 = 2 * hLen + if (mLen > k - hLen2 - 2) { + throw new Error('message too long') + } + var ps = Buffer.alloc(k - mLen - hLen2 - 2) + var dblen = k - hLen - 1 + var seed = randomBytes(hLen) + var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)) + var maskedSeed = xor(seed, mgf(maskedDb, hLen)) + return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)) +} +function pkcs1 (key, msg, reverse) { + var mLen = msg.length + var k = key.modulus.byteLength() + if (mLen > k - 11) { + throw new Error('message too long') + } + var ps + if (reverse) { + ps = Buffer.alloc(k - mLen - 3, 0xff) + } else { + ps = nonZero(k - mLen - 3) + } + return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)) +} +function nonZero (len) { + var out = Buffer.allocUnsafe(len) + var i = 0 + var cache = randomBytes(len * 2) + var cur = 0 + var num + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len * 2) + cur = 0 + } + num = cache[cur++] + if (num) { + out[i++] = num + } + } + return out +} + + +/***/ }), + +/***/ 9247: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BN = __webpack_require__(2509) +var Buffer = (__webpack_require__(2861).Buffer) + +function withPublic (paddedMsg, key) { + return Buffer.from(paddedMsg + .toRed(BN.mont(key.modulus)) + .redPow(new BN(key.publicExponent)) + .fromRed() + .toArray()) +} + +module.exports = withPublic + + +/***/ }), + +/***/ 2061: +/***/ ((module) => { + +module.exports = function xor (a, b) { + var len = a.length + var i = -1 + while (++i < len) { + a[i] ^= b[i] + } + return a +} + + +/***/ }), + +/***/ 3209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); + + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = (__webpack_require__(2861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} + + +/***/ }), + +/***/ 6983: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); + + +function oldBrowser () { + throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') +} +var safeBuffer = __webpack_require__(2861) +var randombytes = __webpack_require__(3209) +var Buffer = safeBuffer.Buffer +var kBufferMaxLength = safeBuffer.kMaxLength +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto +var kMaxUint32 = Math.pow(2, 32) - 1 +function assertOffset (offset, length) { + if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare + throw new TypeError('offset must be a number') + } + + if (offset > kMaxUint32 || offset < 0) { + throw new TypeError('offset must be a uint32') + } + + if (offset > kBufferMaxLength || offset > length) { + throw new RangeError('offset out of range') + } +} + +function assertSize (size, offset, length) { + if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare + throw new TypeError('size must be a number') + } + + if (size > kMaxUint32 || size < 0) { + throw new TypeError('size must be a uint32') + } + + if (size + offset > length || size > kBufferMaxLength) { + throw new RangeError('buffer too small') + } +} +if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync +} else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser +} +function randomFill (buf, offset, size, cb) { + if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + if (typeof offset === 'function') { + cb = offset + offset = 0 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) +} + +function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf +} +function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + assertOffset(offset, buf.length) + + if (size === undefined) size = buf.length - offset + + assertSize(size, offset, buf.length) + + return actualFill(buf, offset, size) +} + + +/***/ }), + +/***/ 6048: +/***/ ((module) => { + +"use strict"; + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.F = codes; + + +/***/ }), + +/***/ 5382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = __webpack_require__(5412); +var Writable = __webpack_require__(6708); +__webpack_require__(6698)(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +/***/ }), + +/***/ 3600: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + + + +module.exports = PassThrough; +var Transform = __webpack_require__(4610); +__webpack_require__(6698)(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +/***/ }), + +/***/ 5412: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(7007).EventEmitter); +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = __webpack_require__(9838); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = __webpack_require__(2726); +var destroyImpl = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +__webpack_require__(6698)(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(5382); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__webpack_require__(3141)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(5382); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__webpack_require__(3141)/* .StringDecoder */ .I); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __webpack_require__(2955); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __webpack_require__(5157); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), + +/***/ 4610: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + + +module.exports = Transform; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = __webpack_require__(5382); +__webpack_require__(6698)(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} + +/***/ }), + +/***/ 6708: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: __webpack_require__(4643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +__webpack_require__(6698)(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(5382); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || __webpack_require__(5382); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; + +/***/ }), + +/***/ 2955: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); + + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = __webpack_require__(6238); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; + +/***/ }), + +/***/ 2726: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = __webpack_require__(8287), + Buffer = _require.Buffer; +var _require2 = __webpack_require__(5340), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); + +/***/ }), + +/***/ 5896: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); + + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; + +/***/ }), + +/***/ 6238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + + +var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(6048)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; + +/***/ }), + +/***/ 5157: +/***/ ((module) => { + +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + + +/***/ }), + +/***/ 7758: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __webpack_require__(6238); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; + +/***/ }), + +/***/ 5291: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__webpack_require__(6048)/* .codes */ .F).ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; + +/***/ }), + +/***/ 345: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(7007).EventEmitter; + + +/***/ }), + +/***/ 8399: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(5412); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(6708); +exports.Duplex = __webpack_require__(5382); +exports.Transform = __webpack_require__(4610); +exports.PassThrough = __webpack_require__(3600); +exports.finished = __webpack_require__(6238); +exports.pipeline = __webpack_require__(7758); + + +/***/ }), + +/***/ 6011: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(8287).Buffer) +var inherits = __webpack_require__(6698) +var HashBase = __webpack_require__(1147) + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} + +module.exports = RIPEMD160 + + +/***/ }), + +/***/ 1147: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(2861).Buffer) +var Transform = (__webpack_require__(8399).Transform) +var inherits = __webpack_require__(6698) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 6897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var define = __webpack_require__(41); +var hasDescriptors = __webpack_require__(592)(); +var gOPD = __webpack_require__(5795); + +var $TypeError = __webpack_require__(9675); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).Buffer) + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var K = [ + 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 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + 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 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).Buffer) + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + + +/***/ }), + +/***/ 8310: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = (__webpack_require__(7007).EventEmitter); +var inherits = __webpack_require__(6698); + +inherits(Stream, EE); +Stream.Readable = __webpack_require__(5412); +Stream.Writable = __webpack_require__(6708); +Stream.Duplex = __webpack_require__(5382); +Stream.Transform = __webpack_require__(4610); +Stream.PassThrough = __webpack_require__(3600); +Stream.finished = __webpack_require__(6238) +Stream.pipeline = __webpack_require__(7758) + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + + +/***/ }), + +/***/ 3141: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = (__webpack_require__(2861).Buffer); +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.I = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), + +/***/ 4643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(6763); + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!__webpack_require__.g.localStorage) return false; + } catch (_) { + return false; + } + var val = __webpack_require__.g.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + + +/***/ }), + +/***/ 1135: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), + +/***/ 9032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +var isArgumentsObject = __webpack_require__(7244); +var isGeneratorFunction = __webpack_require__(8184); +var whichTypedArray = __webpack_require__(5767); +var isTypedArray = __webpack_require__(5680); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === 'undefined') { + return false; + } + + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBufferCopy; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(5606); +/* provided dependency */ var console = __webpack_require__(6763); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').slice(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = __webpack_require__(9032); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(1135); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(6698); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + + +/***/ }), + +/***/ 8961: +/***/ ((__unused_webpack_module, exports) => { + +var indexOf = function (xs, item) { + if (xs.indexOf) return xs.indexOf(item); + else for (var i = 0; i < xs.length; i++) { + if (xs[i] === item) return i; + } + return -1; +}; +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } +}()); + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; + } + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; + } + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); + } + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + if (context) { + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; + }); + } + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.isContext = function (context) { + return context instanceof Context; +}; + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + return copy; +}; + + +/***/ }), + +/***/ 4400: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +module.exports.ModuleBuilder = __webpack_require__(442); +/* unused reexport */ __webpack_require__(8269); +/* unused reexport */ __webpack_require__(7831); + + +/***/ }), + +/***/ 5705: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const utils = __webpack_require__(484); + +class CodeBuilder { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x21, ...utils.varuint32( idx )]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [...valCode, 0x22, ...utils.varuint32( idx )]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [0x20, ...utils.varuint32( idx )]; + } + + i64_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x30, align, ...utils.varuint32(offset)]; + } + + i64_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default + return [...idxCode, 0x31, align, ...utils.varuint32(offset)]; + } + + i64_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x32, align, ...utils.varuint32(offset)]; + } + + i64_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default + return [...idxCode, 0x33, align, ...utils.varuint32(offset)]; + } + + i64_load32_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x34, align, ...utils.varuint32(offset)]; + } + + i64_load32_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x35, align, ...utils.varuint32(offset)]; + } + + i64_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default + return [...idxCode, 0x29, align, ...utils.varuint32(offset)]; + } + + + i64_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 3; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 3; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)]; + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)]; + } + + + i64_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3d, align, ...utils.varuint32(offset)]; + } + + + i64_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3c, align, ...utils.varuint32(offset)]; + } + + i32_load8_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2c, align, ...utils.varuint32(offset)]; + } + + i32_load8_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default + return [...idxCode, 0x2d, align, ...utils.varuint32(offset)]; + } + + i32_load16_s(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2e, align, ...utils.varuint32(offset)]; + } + + i32_load16_u(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default + return [...idxCode, 0x2f, align, ...utils.varuint32(offset)]; + } + + i32_load(idxCode, _offset, _align) { + const offset = _offset || 0; + const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default + return [...idxCode, 0x28, align, ...utils.varuint32(offset)]; + } + + i32_store(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 2; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 2; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)]; + } + + + i32_store16(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 1; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 1; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3b, align, ...utils.varuint32(offset)]; + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (Array.isArray(_offset)) { + offset = 0; + align = 0; + codeVal = _offset; + } else if (Array.isArray(_align)) { + offset = _offset; + align = 0; + codeVal = _align; + } else if (Array.isArray(_codeVal)) { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + return [...idxCode, ...codeVal, 0x3a, align, ...utils.varuint32(offset)]; + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [...[].concat(...args), 0x10, ...utils.varuint32(idx)]; + } + + call_indirect(fnIdx, ...args) { + return [...[].concat(...args), ...fnIdx, 0x11, 0, 0]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b]; + } else { + return [...condCode, 0x04, 0x40, ...thenCode, 0x0b]; + } + } + + block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; } + loop(...args) { + return [0x03, 0x40, ...[].concat(...[...args]), 0x0b]; + } + br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; } + br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; } + ret(rCode) { return [...rCode, 0x0f]; } + drop(dCode) { return [...dCode, 0x1a]; } + + i64_const(num) { return [0x42, ...utils.varint64(num)]; } + i32_const(num) { return [0x41, ...utils.varint32(num)]; } + + + i64_eqz(opcode) { return [...opcode, 0x50]; } + i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; } + i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; } + i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; } + i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; } + i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; } + i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; } + i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; } + i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; } + i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; } + i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; } + i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; } + i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; } + i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; } + i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; } + i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; } + i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; } + i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; } + i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; } + i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; } + i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; } + i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; } + i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; } + i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; } + i64_extend_i32_s(op1code) { return [...op1code, 0xac]; } + i64_extend_i32_u(op1code) { return [...op1code, 0xad]; } + i64_clz(op1code) { return [...op1code, 0x79]; } + i64_ctz(op1code) { return [...op1code, 0x7a]; } + + i32_eqz(op1code) { return [...op1code, 0x45]; } + i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; } + i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; } + i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; } + i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; } + i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; } + i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; } + i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; } + i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; } + i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; } + i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; } + i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; } + i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; } + i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; } + i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; } + i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; } + i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; } + i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; } + i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; } + i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; } + i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; } + i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; } + i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; } + i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; } + i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; } + i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; } + i32_wrap_i64(op1code) { return [...op1code, 0xa7]; } + i32_clz(op1code) { return [...op1code, 0x67]; } + i32_ctz(op1code) { return [...op1code, 0x68]; } + + unreachable() { return [ 0x0 ]; } + + current_memory() { return [ 0x3f, 0]; } + + comment() { return []; } +} + +module.exports = CodeBuilder; + + +/***/ }), + +/***/ 4010: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const utils = __webpack_require__(484); + +class CodeBuilderWat { + constructor(func) { + this.func = func; + this.functionName = func.functionName; + this.module = func.module; + } + + setLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [valCode, `set_local $${localName}`]; + } + + teeLocal(localName, valCode) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return [valCode, `tee_local $${localName}`]; + } + + getLocal(localName) { + const idx = this.func.localIdxByName[localName]; + if (idx === undefined) + throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `); + return `get_local $${localName}`; + } + + genLoad(inst, def_align, idxCode, _offset, _align) { + let S = inst; + const offset = _offset || 0; + if (offset>0) S += ` offset=${offset}`; + const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default + if (align!=def_align) S += ` align=${1 << align}`; + return [idxCode, S]; + } + + + genStore(inst, def_align, idxCode, _offset, _align, _codeVal) { + let offset, align, codeVal; + if (typeof _align === "undefined") { + offset = 0; + align = def_align; + codeVal = _offset; + } else if (typeof _codeVal === "undefined") { + offset = _offset; + align = def_align; + codeVal = _align; + } else { + offset = _offset; + align = _align; + codeVal = _codeVal; + } + let S = inst; + if (offset>0) S += ` offset=${offset}`; + if (align!=def_align) S += ` align=${1 << align}`; + return [idxCode, codeVal, S]; + } + + i64_load8_s(idxCode, _offset, _align) { + return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align); + } + + i64_load8_u(idxCode, _offset, _align) { + return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align); + } + + i64_load16_s(idxCode, _offset, _align) { + return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align); + } + + i64_load16_u(idxCode, _offset, _align) { + return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align); + } + + i64_load32_s(idxCode, _offset, _align) { + return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align); + } + + i64_load32_u(idxCode, _offset, _align) { + return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align); + } + + i64_load(idxCode, _offset, _align) { + return this.genLoad("i64.load", 3, idxCode, _offset, _align); + } + + + i64_store(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal); + } + + i64_store32(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal); + } + + i64_store16(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal); + } + + i64_store8(idxCode, _offset, _align, _codeVal) { + return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal); + } + + i32_load8_s(idxCode, _offset, _align) { + return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align); + } + + i32_load8_u(idxCode, _offset, _align) { + return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align); + } + + i32_load16_s(idxCode, _offset, _align) { + return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align); + } + + i32_load16_u(idxCode, _offset, _align) { + return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align); + } + + i32_load(idxCode, _offset, _align) { + return this.genLoad("i32.load", 2, idxCode, _offset, _align); + } + + i32_store(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal); + } + + i32_store16(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal); + } + + i32_store8(idxCode, _offset, _align, _codeVal) { + return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal); + } + + call(fnName, ...args) { + const idx = this.module.functionIdxByName[fnName]; + if (idx === undefined) + throw new Error(`Function not defined: Function: ${fnName}`); + return [args, `call $${fnName}`]; + } + + call_indirect(fnIdx, ...args) { + return [args, fnIdx, "call_indirect (type 0)"]; + } + + if(condCode, thenCode, elseCode) { + if (elseCode) { + return [condCode, "if", utils.ident(thenCode), "else", utils.ident(elseCode), "end"]; + } else { + return [condCode, "if", utils.ident(thenCode), "end"]; + } + } + + block(bCode) { return ["block", utils.ident(bCode), "end"]; } + loop(...args) { return ["loop", utils.ident(args), "end"]; } + br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; } + br(relPath) { return `br ${relPath}`; } + ret(rCode) { return [rCode, "return"]; } + drop(dCode) { return [dCode, "drop"]; } + + i64_const(num) { return `i64.const ${num}`; } + i32_const(num) { return `i32.const ${num}`; } + + i64_eqz(opcode) { return [opcode, "i64.eqz"]; } + i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; } + i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; } + i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; } + i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; } + i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; } + i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; } + i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; } + i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; } + i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; } + i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; } + i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; } + i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; } + i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; } + i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; } + i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; } + i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; } + i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; } + i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; } + i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; } + i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; } + i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; } + i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; } + i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; } + i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; } + i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; } + + + i32_eqz(op1code) { return [op1code, "i32.eqz"]; } + i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; } + i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; } + i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; } + i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; } + i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; } + i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; } + i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; } + i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; } + i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; } + i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; } + i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; } + i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; } + i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; } + i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; } + i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; } + i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; } + i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; } + i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; } + i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; } + i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; } + i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; } + i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; } + i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; } + i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; } + i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; } + i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; } + + ureachable() { return "unreachable"; } + + current_memory() { return "current_memory"; } + + comment(c) { return ";; " + c; } + +} + +module.exports = CodeBuilderWat; + + +/***/ }), + +/***/ 5986: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const CodeBuilder = __webpack_require__(5705); +const utils = __webpack_require__(484); + +const typeCodes = { + "i32": 0x7f, + "i64": 0x7e, + "f32": 0x7d, + "f64": 0x7c, + "anyfunc": 0x70, + "func": 0x60, + "emptyblock": 0x40 +}; + + +class FunctionBuilder { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType + }); + } + + addLocal(localName, localType, _length) { + const length = _length || 1; + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + length: length + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])]; + const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0]; + return [0x60, ...params, ...returns]; + } + + getBody() { + const locals = this.locals.map((l) => [ + ...utils.varuint32(l.length), + typeCodes[l.type] + ]); + + const body = [ + ...utils.varuint32(this.locals.length), + ...[].concat(...locals), + ...this.code, + 0x0b + ]; + return [ + ...utils.varuint32(body.length), + ...body + ]; + } + + addCode(...code) { + this.code.push(...[].concat(...[...code])); + } + + getCodeBuilder() { + return new CodeBuilder(this); + } +} + +module.exports = FunctionBuilder; + + +/***/ }), + +/***/ 2341: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const CodeBuilderWat = __webpack_require__(4010); +const utils = __webpack_require__(484); + +class FunctionBuilderWat { + + constructor (module, fnName, fnType, moduleName, fieldName) { + if (fnType == "import") { + this.fnType = "import"; + this.moduleName = moduleName; + this.fieldName = fieldName; + } else if (fnType == "internal") { + this.fnType = "internal"; + this.comment = moduleName; + } else { + throw new Error("Invalid function fnType: " + fnType); + } + this.module = module; + this.fnName = fnName; + this.params = []; + this.locals = []; + this.localIdxByName = {}; + this.code = []; + this.returnType = null; + this.nextLocal =0; + } + + addParam(paramName, paramType) { + if (this.localIdxByName[paramName]) + throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `); + const idx = this.nextLocal++; + this.localIdxByName[paramName] = idx; + this.params.push({ + type: paramType, + name: paramName + }); + } + + addLocal(localName, localType, _length) { + if ((typeof _length != "undefined") && (_length != 1)) { + throw new Error("Locals greater than 1 not implemented"); + } + if (this.localIdxByName[localName]) + throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `); + const idx = this.nextLocal++; + this.localIdxByName[localName] = idx; + this.locals.push({ + type: localType, + name: localName, + }); + } + + setReturnType(returnType) { + if (this.returnType) + throw new Error(`returnType already defined. Function: ${this.fnName}`); + this.returnType = returnType; + } + + getSignature() { + let p = ""; + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const FunctionBuilder = __webpack_require__(5986); +const utils = __webpack_require__(484); + +class ModuleBuilder { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + this._setSignatures(); + return new Uint8Array([ + ...utils.u32(0x6d736100), + ...utils.u32(1), + ...this._buildType(), + ...this._buildImport(), + ...this._buildFunctionDeclarations(), + ...this._buildFunctionsTable(), + ...this._buildExports(), + ...this._buildElements(), + ...this._buildCode(), + ...this._buildData() + ]); + } + + addFunction(fnName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "internal")); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new globalThis.TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = "s_"+utils.toHexString(signature); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + + +const FunctionBuilderWat = __webpack_require__(2341); +const utils = __webpack_require__(484); + +class ModuleBuilderWat { + + constructor() { + this.functions = []; + this.functionIdxByName = {}; + this.nImportFunctions = 0; + this.nInternalFunctions =0; + this.memory = { + pagesSize: 1, + moduleName: "env", + fieldName: "memory" + }; + this.free = 8; + this.datas = []; + this.modules = {}; + this.exports = []; + this.functionsTable = []; + } + + build() { + const src = []; + this._setSignatures(); + src.push(this._buildType()); + src.push(this._buildImport()); + if (this.functionsTable.length>0) { + src.push(this._buildFunctionsTable()); + } + if (this.exports.length > 0) { + src.push(this._buildExports()); + } + if (this.functionsTable.length>0) { + src.push(this._buildElements()); + } + if (this.nInternalFunctions>0) { + src.push(this._buildFunctions()); + } + src.push(this._buildData()); + return [ + "(module", + utils.ident(src), + ")" + ]; + } + + addFunction(fnName, comment) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment)); + + this.nInternalFunctions++; + return this.functions[idx]; + } + + addIimportFunction(fnName, moduleName, _fieldName) { + if (typeof(this.functionIdxByName[fnName]) !== "undefined") + throw new Error(`Function already defined: ${fnName}`); + + if ( (this.functions.length>0) + &&(this.functions[this.functions.length-1].type == "internal")) + throw new Error(`Import functions must be declared before internal: ${fnName}`); + + let fieldName = _fieldName || fnName; + + const idx = this.functions.length; + this.functionIdxByName[fnName] = idx; + + this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName)); + + this.nImportFunctions ++; + return this.functions[idx]; + } + + setMemory(pagesSize, moduleName, fieldName) { + this.memory = { + pagesSize: pagesSize, + moduleName: moduleName || "env", + fieldName: fieldName || "memory" + }; + } + + exportFunction(fnName, _exportName) { + const exportName = _exportName || fnName; + if (typeof(this.functionIdxByName[fnName]) === "undefined") + throw new Error(`Function not defined: ${fnName}`); + const idx = this.functionIdxByName[fnName]; + if (exportName != fnName) { + this.functionIdxByName[exportName] = idx; + } + this.exports.push({ + exportName: exportName, + idx: idx + }); + } + + addFunctionToTable(fnName) { + const idx = this.functionIdxByName[fnName]; + this.functionsTable.push(idx); + } + + addData(offset, bytes) { + this.datas.push({ + offset: offset, + bytes: bytes + }); + } + + alloc(a, b) { + let size; + let bytes; + if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) { + size = a.length; + bytes = a; + } else { + size = a; + bytes = b; + } + size = (((size-1)>>3) +1)<<3; // Align to 64 bits. + const p = this.free; + this.free += size; + if (bytes) { + this.addData(p, bytes); + } + return p; + } + + allocString(s) { + const encoder = new TextEncoder(); + const uint8array = encoder.encode(s); + return this.alloc([...uint8array, 0]); + } + + _setSignatures() { + this.signatures = []; + const signatureIdxByName = {}; + if (this.functionsTable.length>0) { + const signature = this.functions[this.functionsTable[0]].getSignature(); + const signatureName = this.functions[this.functionsTable[0]].getSignatureName(); + signatureIdxByName[signatureName] = 0; + this.signatures.push(signature); + } + for (let i=0; i126 || b[i] == 34 || b[i]==92) { + let h=b[i].toString(16); + while (h.length<2) h = "0"+h; + S += "\\" + h; + } else { + S += String.fromCharCode(b[i]); + } + } + S += "\""; + return S; + } + } + +} + +module.exports = ModuleBuilderWat; + + +/***/ }), + +/***/ 7831: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var console = __webpack_require__(6763); +/* + Copyright 2019 0KIMS association. + + This file is part of websnark (Web Assembly zkSnark Prover). + + websnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + websnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with websnark. If not, see . +*/ + +/* globals WebAssembly */ +const bigInt = __webpack_require__(2096); +const ModuleBuilder = __webpack_require__(442); + +function buf2hex(buffer) { // buffer is an ArrayBuffer + return Array.prototype.map.call(new Uint8Array(buffer), x => ("00" + x.toString(16)).slice(-2)).join(""); +} + + +async function buildProtoboard(builder, defBytes, bitsPerBytes) { + const protoboard = new Protoboard(); + + protoboard.defBytes = defBytes; + protoboard.bitsPerBytes = bitsPerBytes || 32; + + protoboard.memory = new WebAssembly.Memory({initial:20000}); + protoboard.i32 = new Uint32Array(protoboard.memory.buffer); + protoboard.i8 = new Uint8Array(protoboard.memory.buffer); + + const moduleBuilder = new ModuleBuilder(); + + const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32"); + fLog32.addParam("x", "i32"); + const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64"); + fLog64.addParam("x", "i32"); + fLog64.addParam("y", "i32"); + + buildLog32(moduleBuilder); + buildLog64(moduleBuilder); + + builder(moduleBuilder, protoboard); + + + const code = moduleBuilder.build(); + + const wasmModule = await WebAssembly.compile(code); + + protoboard.log = console.log; + + protoboard.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": protoboard.memory + }, + debug: { + log32: function (c1) { + if (c1<0) c1 = 0x100000000+c1; + let s=c1.toString(16); + while (s.length<8) s = "0"+s; + protoboard.log(s + ": " + c1.toString()); + }, + log64: function (c1, c2) { + if (c1<0) c1 = 0x100000000+c1; + if (c2<0) c2 = 0x100000000+c2; + const n = bigInt(c1) + bigInt(c2).shiftLeft(32); + let s=n.toString(16); + while (s.length<16) s = "0"+s; + protoboard.log(s + ": " + n.toString()); + } + } + }); + + Object.assign(protoboard, protoboard.instance.exports); + Object.assign(protoboard, moduleBuilder.modules); + + return protoboard; + + function buildLog32(module) { + + const f = module.addFunction("log32"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call("debug_log32", c.getLocal("x"))); + } + + function buildLog64(module) { + + const f = module.addFunction("log64"); + f.addParam("x", "i64"); + + const c = f.getCodeBuilder(); + f.addCode(c.call( + "debug_log64", + c.i32_wrap_i64(c.getLocal("x")), + c.i32_wrap_i64( + c.i64_shr_u( + c.getLocal("x"), + c.i64_const(32) + ) + ) + )); + } + +} + +class Protoboard { + + constructor() { + + } + + alloc(length) { + if (typeof length === "undefined") { + length = this.defBytes; + } + length = (((length-1)>>3) +1)<<3; // Align to 64 bits. + + const res = this.i32[0]; + this.i32[0] += length; + return res; + } + + set(pos, nums, nBytes) { + if (!Array.isArray(nums)) { + nums = [nums]; + } + if (typeof nBytes === "undefined") { + nBytes = this.defBytes; + } + + const words = Math.floor((nBytes -1)/4)+1; + let p = pos; + + const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); + + for (let i=0; i>2] = rd.remainder.toJSNumber(); + v = rd.quotient; + p += 4; + } + if (!v.isZero()) { + throw new Error('Expected v to be 0'); + } +/* this.i32[p>>2] = bigInt(nums[i]).shiftRight( (words-1)*this.bitsPerBytes).toJSNumber(); + p += 4; +*/ } + + return pos; + } + + get(pos, nElements, nBytes) { + if (typeof nBytes == "undefined") { + if (typeof nElements == "undefined") { + nElements = 1; + nBytes = this.defBytes; + } else { + nElements = nBytes; + nBytes = this.defBytes; + } + } + + const words = Math.floor((nBytes -1)/4)+1; + + const CHUNK = bigInt.one.shiftLeft(this.bitsPerBytes); + + + const nums = []; + for (let i=0; i=0; j--) { + acc = acc.times(CHUNK); + let v = this.i32[(pos>>2)+j]; + if (this.bitsPerBytes <32) { + if (v&0x80000000) v = v-0x100000000; + } + acc = acc.add(v); + } + nums.push(acc); + pos += words*4; + } + + if (nums.length == 1) return nums[0]; + return nums; + } +} + +module.exports = buildProtoboard; + + +/***/ }), + +/***/ 484: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmbuilder + + wasmbuilder is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmbuilder is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmbuilder. If not, see . +*/ + +const bigInt = __webpack_require__(2096); + +function toNumber(n) { + let v; + if (typeof n=="string") { + if (n.slice(0,2).toLowerCase() == "0x") { + v = bigInt(n.slice(2),16); + } else { + v = bigInt(n); + } + } else { + v = bigInt(n); + } + return v; +} + +function u32(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + return b; +} + +function u64(n) { + const b = []; + const v = toNumber(n); + b.push(v.and(0xFF).toJSNumber()); + b.push(v.shiftRight(8).and(0xFF).toJSNumber()); + b.push(v.shiftRight(16).and(0xFF).toJSNumber()); + b.push(v.shiftRight(24).and(0xFF).toJSNumber()); + b.push(v.shiftRight(32).and(0xFF).toJSNumber()); + b.push(v.shiftRight(40).and(0xFF).toJSNumber()); + b.push(v.shiftRight(48).and(0xFF).toJSNumber()); + b.push(v.shiftRight(56).and(0xFF).toJSNumber()); + return b; +} + +function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; +} + +function string(str) { + const bytes = toUTF8Array(str); + return [ ...varuint32(bytes.length), ...bytes ]; +} + +function varuint(n) { + const code = []; + let v = toNumber(n); + if (v.isNegative()) throw new Error("Number cannot be negative"); + while (!v.isZero()) { + code.push(v.and(0x7F).toJSNumber()); + v = v.shiftRight(7); + } + if (code.length==0) code.push(0); + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + + +// module.exports.bn128_wasm = require("./build/bn128_wasm.js"); +// module.exports.bls12381_wasm = require("./build/bls12381_wasm.js"); +// module.exports.mnt6753_wasm = require("./build/mnt6753_wasm.js"); + +module.exports.buildBn128 = __webpack_require__(3584); +module.exports.buildBls12381 = __webpack_require__(6920); +// module.exports.buildMnt6753 = require("./src/mnt6753/build_mnt7.js"); + + +/***/ }), + +/***/ 6920: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const bigInt = __webpack_require__(2096); +const utils = __webpack_require__(2333); + +const buildF1m =__webpack_require__(75); +const buildF1 =__webpack_require__(8138); +const buildF2m =__webpack_require__(5420); +const buildF3m =__webpack_require__(7173); +const buildCurve =__webpack_require__(5904); +const buildFFT = __webpack_require__(3911); +const buildPol = __webpack_require__(2896); +const buildQAP = __webpack_require__(637); +const buildApplyKey = __webpack_require__(3320); + +// Definition here: https://electriccoin.co/blog/new-snark-curve/ + +module.exports = function buildBLS12381(module, _prefix) { + + const prefix = _prefix || "bls12381"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = bigInt("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); + const r = bigInt("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); + + const n64q = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8q = n64q*8; + const f1size = n8q; + const f2size = f1size * 2; + const f6size = f1size * 6; + const ftsize = f1size * 12; + + const n64r = Math.floor((r.minus(1).bitLength() - 1)/64) +1; + const n8r = n64r*8; + const frsize = n8r; + + + const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m(module, q, "f1m", "intq"); + buildF1(module, r, "fr", "frm", "intr"); + const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(4)), f1size )); + const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); + + buildFFT(module, "frm", "frm", "frm", "frm_mul"); + + buildPol(module, "pol", "frm"); + buildQAP(module, "qap", "frm"); + + const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(bigInt("4")), f1size ) + ]); + const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8r)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8r), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8r, n8r, n8r, "frm_mul"); + buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8q*3, n8q*3, n8r, "g1m_timesFr"); + buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8q*2, n8q*3, n8r, "g1m_timesFrAffine"); + buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8q*2*3, n8q*3*2, n8r, "g2m_timesFr"); + buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8q*2*2, n8q*3*2, n8r, "g2m_timesFrAffine"); + + + function toMontgomery(a) { + return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); + } + + const G1gen = [ + bigInt("3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507"), + bigInt("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569"), + bigInt.one + ]; + + const pG1gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + bigInt.zero, + bigInt.one, + bigInt.zero + ]; + + const pG1zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + bigInt("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), + bigInt("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758"), + ],[ + bigInt("1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905"), + bigInt("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582"), + ],[ + bigInt.one, + bigInt.zero, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + bigInt.zero, + bigInt.zero, + ],[ + bigInt.one, + bigInt.zero, + ],[ + bigInt.zero, + bigInt.zero, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), + ...utils.bigInt2BytesLE( bigInt(0), f1size ) + ]); + + const pBls12381Twist = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwistCoefB = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("4"), f1size ), + ]); + + function build_mulNR2() { + const f = module.addFunction(f2mPrefix + "_mulNR"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x0c = c.i32_const(module.alloc(f1size)); + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1size)); + const r0 = c.getLocal("pr"); + const r1 = c.i32_add(c.getLocal("pr"), c.i32_const(f1size)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, x0c), + c.call(f1mPrefix+"_sub", x0, x1, r0), + c.call(f1mPrefix+"_add", x0c, x1, r1), + ); + } + build_mulNR2(); + + const f6mPrefix = buildF3m(module, f2mPrefix+"_mulNR", "f6m", "f2m"); + + function build_mulNR6() { + const f = module.addFunction(f6mPrefix + "_mulNR"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const c0copy = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c0copy + ), + c.call( + f2mPrefix + "_mulNR", + c.i32_add(c.getLocal("x"), c.i32_const(n8q*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8q*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8q*4)), + ), + c.call( + f2mPrefix + "_copy", + c0copy, + c.i32_add(c.getLocal("pr"), c.i32_const(n8q*2)), + ), + ); + } + build_mulNR6(); + + const ftmPrefix = buildF2m(module, f6mPrefix+"_mulNR", "ftm", f6mPrefix); + + const ateLoopCount = bigInt("d201000000010000", 16); + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + const isLoopNegative = true; + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8q; + const preQSize = 3*n8q*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = true; + + const finalExpZ = bigInt("15132376222941642752"); + + + module.modules[prefix] = { + n64q: n64q, + n64r: n64r, + n8q: n8q, + n8r: n8r, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + r: r, + q: q, + prePSize: prePSize, + preQSize: preQSize + }; + + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("R", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const t0 = c.getLocal("r"); + const t3 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t6 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + + const zsquared = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // tmp0 = r.x.square(); + c.call(f2mPrefix + "_square", Rx, t0), + + // tmp1 = r.y.square(); + c.call(f2mPrefix + "_square", Ry, t1), + + // tmp2 = tmp1.square(); + c.call(f2mPrefix + "_square", t1, t2), + + // tmp3 = (tmp1 + r.x).square() - tmp0 - tmp2; + c.call(f2mPrefix + "_add", t1, Rx, t3), + c.call(f2mPrefix + "_square", t3, t3), + c.call(f2mPrefix + "_sub", t3, t0, t3), + c.call(f2mPrefix + "_sub", t3, t2, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp4 = tmp0 + tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t4), + c.call(f2mPrefix + "_add", t4, t0, t4), + + // tmp6 = r.x + tmp4; + c.call(f2mPrefix + "_add", Rx, t4, t6), + + // tmp5 = tmp4.square(); + c.call(f2mPrefix + "_square", t4, t5), + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // r.x = tmp5 - tmp3 - tmp3; + c.call(f2mPrefix + "_sub", t5, t3, Rx), + c.call(f2mPrefix + "_sub", Rx, t3, Rx), + + // r.z = (r.z + r.y).square() - tmp1 - zsquared; + c.call(f2mPrefix + "_add", Rz, Ry, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, t1, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + + // r.y = (tmp3 - r.x) * tmp4; + c.call(f2mPrefix + "_sub", t3, Rx, Ry), + c.call(f2mPrefix + "_mul", Ry, t4, Ry), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // tmp2 = tmp2 + tmp2; + c.call(f2mPrefix + "_add", t2, t2, t2), + + // r.y -= tmp2; + c.call(f2mPrefix + "_sub", Ry, t2, Ry), + + // tmp3 = tmp4 * zsquared; + c.call(f2mPrefix + "_mul", t4, zsquared, t3), + + // tmp3 = tmp3 + tmp3; + c.call(f2mPrefix + "_add", t3, t3, t3), + + // tmp3 = -tmp3; + c.call(f2mPrefix + "_neg", t3, t3), + + // tmp6 = tmp6.square() - tmp0 - tmp5; + c.call(f2mPrefix + "_square", t6, t6), + c.call(f2mPrefix + "_sub", t6, t0, t6), + c.call(f2mPrefix + "_sub", t6, t5, t6), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp1 = tmp1 + tmp1; + c.call(f2mPrefix + "_add", t1, t1, t1), + + // tmp6 = tmp6 - tmp1; + c.call(f2mPrefix + "_sub", t6, t1, t6), + + // tmp0 = r.z * zsquared; + c.call(f2mPrefix + "_mul", Rz, zsquared, t0), + + // tmp0 = tmp0 + tmp0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("R", "i32"); + f.addParam("Q", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const Rx = c.getLocal("R"); + const Ry = c.i32_add(c.getLocal("R"), c.i32_const(2*n8q)); + const Rz = c.i32_add(c.getLocal("R"), c.i32_const(4*n8q)); + + const Qx = c.getLocal("Q"); + const Qy = c.i32_add(c.getLocal("Q"), c.i32_const(2*n8q)); + + const t10 = c.getLocal("r"); + const t1 = c.i32_add(c.getLocal("r"), c.i32_const(2*n8q)); + const t9 = c.i32_add(c.getLocal("r"), c.i32_const(4*n8q)); + + const zsquared = c.i32_const(module.alloc(f2size)); + const ysquared = c.i32_const(module.alloc(f2size)); + const ztsquared = c.i32_const(module.alloc(f2size)); + const t0 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const t6 = c.i32_const(module.alloc(f2size)); + const t7 = c.i32_const(module.alloc(f2size)); + const t8 = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // zsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, zsquared), + + // ysquared = q.y.square(); + c.call(f2mPrefix + "_square", Qy, ysquared), + + // t0 = zsquared * q.x; + c.call(f2mPrefix + "_mul", zsquared, Qx, t0), + + // t1 = ((q.y + r.z).square() - ysquared - zsquared) * zsquared; + c.call(f2mPrefix + "_add", Qy, Rz, t1), + c.call(f2mPrefix + "_square", t1, t1), + c.call(f2mPrefix + "_sub", t1, ysquared, t1), + c.call(f2mPrefix + "_sub", t1, zsquared, t1), + c.call(f2mPrefix + "_mul", t1, zsquared, t1), + + // t2 = t0 - r.x; + c.call(f2mPrefix + "_sub", t0, Rx, t2), + + // t3 = t2.square(); + c.call(f2mPrefix + "_square", t2, t3), + + // t4 = t3 + t3; + c.call(f2mPrefix + "_add", t3, t3, t4), + + // t4 = t4 + t4; + c.call(f2mPrefix + "_add", t4, t4, t4), + + // t5 = t4 * t2; + c.call(f2mPrefix + "_mul", t4, t2, t5), + + // t6 = t1 - r.y - r.y; + c.call(f2mPrefix + "_sub", t1, Ry, t6), + c.call(f2mPrefix + "_sub", t6, Ry, t6), + + // t9 = t6 * q.x; + c.call(f2mPrefix + "_mul", t6, Qx, t9), + + // t7 = t4 * r.x; + c.call(f2mPrefix + "_mul", t4, Rx, t7), + + // r.x = t6.square() - t5 - t7 - t7; + c.call(f2mPrefix + "_square", t6, Rx), + c.call(f2mPrefix + "_sub", Rx, t5, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + c.call(f2mPrefix + "_sub", Rx, t7, Rx), + + // r.z = (r.z + t2).square() - zsquared - t3; + c.call(f2mPrefix + "_add", Rz, t2, Rz), + c.call(f2mPrefix + "_square", Rz, Rz), + c.call(f2mPrefix + "_sub", Rz, zsquared, Rz), + c.call(f2mPrefix + "_sub", Rz, t3, Rz), + + // t10 = q.y + r.z; + c.call(f2mPrefix + "_add", Qy, Rz, t10), + + // t8 = (t7 - r.x) * t6; + c.call(f2mPrefix + "_sub", t7, Rx, t8), + c.call(f2mPrefix + "_mul", t8, t6, t8), + + // t0 = r.y * t5; + c.call(f2mPrefix + "_mul", Ry, t5, t0), + + // t0 = t0 + t0; + c.call(f2mPrefix + "_add", t0, t0, t0), + + // r.y = t8 - t0; + c.call(f2mPrefix + "_sub", t8, t0, Ry), + + // t10 = t10.square() - ysquared; + c.call(f2mPrefix + "_square", t10, t10), + c.call(f2mPrefix + "_sub", t10, ysquared, t10), + + // ztsquared = r.z.square(); + c.call(f2mPrefix + "_square", Rz, ztsquared), + + // t10 = t10 - ztsquared; + c.call(f2mPrefix + "_sub", t10, ztsquared, t10), + + // t9 = t9 + t9 - t10; + c.call(f2mPrefix + "_add", t9, t9, t9), + c.call(f2mPrefix + "_sub", t9, t10, t9), + + // t10 = r.z + r.z; + c.call(f2mPrefix + "_add", Rz, Rz, t10), + + // t6 = -t6; + c.call(f2mPrefix + "_neg", t6, t6), + + // t1 = t6 + t6; + c.call(f2mPrefix + "_add", t6, t6, t1), + ); + } + + + function buildPrepareG2() { + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + + const Q = c.getLocal("pQ"); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + + const base = c.getLocal("ppreQ"); + + f.addCode( + c.call(g2mPrefix + "_normalize", Q, base), + c.if( + c.call(g2mPrefix + "_isZero", base), + c.ret([]) + ), + c.call(g2mPrefix + "_copy", base, R), + c.setLocal("pCoef", c.i32_add(c.getLocal("ppreQ"), c.i32_const(f2size*3))), + ); + + f.addCode( + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", R, base, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildF6Mul1() { + const f = module.addFunction(f6mPrefix+ "_mul1"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const b_b = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac1_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c1, A_c2, Ac1_Ac2), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac1_Ac2, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue(); + c.call(f2mPrefix + "_mulNR", t1, t1), + + // let t2 = (self.c0 + self.c1) * c1 - b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac1, c1, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + ); + } + buildF6Mul1(); + + function buildF6Mul01() { + const f = module.addFunction(f6mPrefix+ "_mul01"); + f.addParam("pA", "i32"); // F6 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pR", "i32"); // F6 + + const c = f.getCodeBuilder(); + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*2)); + const A_c2 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*4)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + + const t1 = c.getLocal("pR"); + const t2 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*2)); + const t3 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*4)); + + const a_a = c.i32_const(module.alloc(f1size*2)); + const b_b = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac1 = c.i32_const(module.alloc(f1size*2)); + const Ac0_Ac2 = c.i32_const(module.alloc(f1size*2)); + + f.addCode( + // let a_a = self.c0 * c0; + c.call(f2mPrefix + "_mul", A_c0, c0, a_a), + + // let b_b = self.c1 * c1; + c.call(f2mPrefix + "_mul", A_c1, c1, b_b), + + + c.call(f2mPrefix + "_add", A_c0, A_c1, Ac0_Ac1), + c.call(f2mPrefix + "_add", A_c0, A_c2, Ac0_Ac2), + + // let t1 = (self.c1 + self.c2) * c1 - b_b; + c.call(f2mPrefix + "_add", A_c1, A_c2, t1), + c.call(f2mPrefix + "_mul", t1, c1, t1), + c.call(f2mPrefix + "_sub", t1, b_b, t1), + + // let t1 = t1.mul_by_nonresidue() + a_a; + c.call(f2mPrefix + "_mulNR", t1, t1), + c.call(f2mPrefix + "_add", t1, a_a, t1), + + // let t2 = (c0 + c1) * (self.c0 + self.c1) - a_a - b_b; + c.call(f2mPrefix + "_add", c0, c1, t2), + c.call(f2mPrefix + "_mul", t2, Ac0_Ac1, t2), + c.call(f2mPrefix + "_sub", t2, a_a, t2), + c.call(f2mPrefix + "_sub", t2, b_b, t2), + + // let t3 = (self.c0 + self.c2) * c0 - a_a + b_b; + c.call(f2mPrefix + "_mul", Ac0_Ac2, c0, t3), + c.call(f2mPrefix + "_sub", t3, a_a, t3), + c.call(f2mPrefix + "_add", t3, b_b, t3), + + + ); + } + buildF6Mul01(); + + + function buildF12Mul014() { + + const f = module.addFunction(ftmPrefix+ "_mul014"); + f.addParam("pA", "i32"); // F12 + f.addParam("pC0", "i32"); // F2 + f.addParam("pC1", "i32"); // F2 + f.addParam("pC4", "i32"); // F2 + f.addParam("pR", "i32"); // F12 + + const c = f.getCodeBuilder(); + + + const A_c0 = c.getLocal("pA"); + const A_c1 = c.i32_add(c.getLocal("pA"), c.i32_const(f1size*6)); + + const c0 = c.getLocal("pC0"); + const c1 = c.getLocal("pC1"); + const c4 = c.getLocal("pC4"); + + const aa = c.i32_const(module.alloc(f1size*6)); + const bb = c.i32_const(module.alloc(f1size*6)); + const o = c.i32_const(module.alloc(f1size*2)); + + const R_c0 = c.getLocal("pR"); + const R_c1 = c.i32_add(c.getLocal("pR"), c.i32_const(f1size*6)); + + f.addCode( + // let aa = self.c0.mul_by_01(c0, c1); + c.call(f6mPrefix + "_mul01", A_c0, c0, c1, aa), + + // let bb = self.c1.mul_by_1(c4); + c.call(f6mPrefix + "_mul1", A_c1, c4, bb), + + // let o = c1 + c4; + c.call(f2mPrefix + "_add", c1, c4, o), + + // let c1 = self.c1 + self.c0; + c.call(f6mPrefix + "_add", A_c1, A_c0, R_c1), + + // let c1 = c1.mul_by_01(c0, &o); + c.call(f6mPrefix + "_mul01", R_c1, c0, o, R_c1), + + // let c1 = c1 - aa - bb; + c.call(f6mPrefix + "_sub", R_c1, aa, R_c1), + c.call(f6mPrefix + "_sub", R_c1, bb, R_c1), + + // let c0 = bb; + c.call(f6mPrefix + "_copy", bb, R_c0), + + // let c0 = c0.mul_by_nonresidue(); + c.call(f6mPrefix + "_mulNR", R_c0, R_c0), + + // let c0 = c0 + aa; + c.call(f6mPrefix + "_add", R_c0, aa, R_c0), + ); + } + buildF12Mul014(); + + + function buildELL() { + const f = module.addFunction(prefix+ "_ell"); + f.addParam("pP", "i32"); + f.addParam("pCoefs", "i32"); + f.addParam("pF", "i32"); + + const c = f.getCodeBuilder(); + + const Px = c.getLocal("pP"); + const Py = c.i32_add(c.getLocal("pP"), c.i32_const(n8q)); + + const F = c.getLocal("pF"); + + const coef0_0 = c.getLocal("pCoefs"); + const coef0_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size)); + const coef1_0 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*2)); + const coef1_1 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*3)); + const coef2 = c.i32_add(c.getLocal("pCoefs"), c.i32_const(f1size*4)); + + const pc0 = module.alloc(f1size*2); + const c0 = c.i32_const(pc0); + const c0_c0 = c.i32_const(pc0); + const c0_c1 = c.i32_const(pc0+f1size); + + const pc1 = module.alloc(f1size*2); + const c1 = c.i32_const(pc1); + const c1_c0 = c.i32_const(pc1); + const c1_c1 = c.i32_const(pc1+f1size); + f.addCode( + // let mut c0 = coeffs.0; + // let mut c1 = coeffs.1; + // + // c0.c0 *= p.y; + // c0.c1 *= p.y; + // + // c1.c0 *= p.x; + // c1.c1 *= p.x; + // + // f.mul_by_014(&coeffs.2, &c1, &c0) + + c.call(f1mPrefix + "_mul", coef0_0, Py, c0_c0), + c.call(f1mPrefix + "_mul", coef0_1, Py, c0_c1), + c.call(f1mPrefix + "_mul", coef1_0, Px, c1_c0), + c.call(f1mPrefix + "_mul", coef1_1, Px, c1_c1), + + c.call(ftmPrefix + "_mul014", F, coef2, c1, c0, F), + + ); + + } + buildELL(); + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP = c.getLocal("ppreP"); + const preQ = c.getLocal("ppreQ"); + + const coefs = c.getLocal("pCoef"); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.if( + c.call(g1mPrefix + "_isZero", preP), + c.ret([]) + ), + c.if( + c.call(g1mPrefix + "_isZero", c.getLocal("ppreQ")), + c.ret([]) + ), + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(prefix + "_ell", preP, coefs, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_ell", preP, coefs, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.call(ftmPrefix + "_square", F, F), + + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.i32_const(1) )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + c.call(prefix + "_ell", preP, coefs, F), + + ); + + + if (isLoopNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", F, F), + ); + } + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760"), bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], + [bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530"), bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557"), bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230")], + [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], + [bigInt("151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027"), bigInt("3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257"), bigInt("2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], + [bigInt("877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230"), bigInt("3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557")], + ] + ]; + + const F6 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("0"), bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("0"), bigInt("1")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("0"), bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437"), bigInt("0")], + [bigInt("4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436"), bigInt("0")], + [bigInt("4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786"), bigInt("0")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350"), bigInt("0")], + [bigInt("793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351"), bigInt("0")], + ] + ]; + + const f = module.addFunction(ftmPrefix + "_frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils.bigInt2BytesLE(toMontgomery(coef[0]), n8q), + ...utils.bigInt2BytesLE(toMontgomery(coef[1]), n8q), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt(a[0]); + const ac1 = bigInt(a[1]); + const bc0 = bigInt(b[0]); + const bc1 = bigInt(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mulNR", x1, t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mulNR", x3, t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mulNR", x5, t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mulNR", tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pBls12381Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, isExpNegative, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + // const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, n8)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + if (isExpNegative) { + f.addCode( + c.call(ftmPrefix + "_conjugate", res, res), + ); + } + + } + + function buildFinalExponentiation() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, finalExpIsNegative, "w0"); + + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const res = c.getLocal("r"); + const t0 = c.i32_const(module.alloc(ftsize)); + const t1 = c.i32_const(module.alloc(ftsize)); + const t2 = c.i32_const(module.alloc(ftsize)); + const t3 = c.i32_const(module.alloc(ftsize)); + const t4 = c.i32_const(module.alloc(ftsize)); + const t5 = c.i32_const(module.alloc(ftsize)); + const t6 = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + // let mut t0 = f.frobenius_map(6) + c.call(ftmPrefix + "_frobeniusMap6", elt, t0), + + // let t1 = f.invert() + c.call(ftmPrefix + "_inverse", elt, t1), + + // let mut t2 = t0 * t1; + c.call(ftmPrefix + "_mul", t0, t1, t2), + + // t1 = t2.clone(); + c.call(ftmPrefix + "_copy", t2, t1), + + // t2 = t2.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t2, t2), + + // t2 *= t1; + c.call(ftmPrefix + "_mul", t2, t1, t2), + + + // t1 = cyclotomic_square(t2).conjugate(); + c.call(prefix + "__cyclotomicSquare", t2, t1), + c.call(ftmPrefix + "_conjugate", t1, t1), + + // let mut t3 = cycolotomic_exp(t2); + c.call(prefix + "__cyclotomicExp_w0", t2, t3), + + // let mut t4 = cyclotomic_square(t3); + c.call(prefix + "__cyclotomicSquare", t3, t4), + + // let mut t5 = t1 * t3; + c.call(ftmPrefix + "_mul", t1, t3, t5), + + // t1 = cycolotomic_exp(t5); + c.call(prefix + "__cyclotomicExp_w0", t5, t1), + + // t0 = cycolotomic_exp(t1); + c.call(prefix + "__cyclotomicExp_w0", t1, t0), + + // let mut t6 = cycolotomic_exp(t0); + c.call(prefix + "__cyclotomicExp_w0", t0, t6), + + // t6 *= t4; + c.call(ftmPrefix + "_mul", t6, t4, t6), + + // t4 = cycolotomic_exp(t6); + c.call(prefix + "__cyclotomicExp_w0", t6, t4), + + // t5 = t5.conjugate(); + c.call(ftmPrefix + "_conjugate", t5, t5), + + // t4 *= t5 * t2; + c.call(ftmPrefix + "_mul", t4, t5, t4), + c.call(ftmPrefix + "_mul", t4, t2, t4), + + // t5 = t2.conjugate(); + c.call(ftmPrefix + "_conjugate", t2, t5), + + // t1 *= t2; + c.call(ftmPrefix + "_mul", t1, t2, t1), + + // t1 = t1.frobenius_map().frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap3", t1, t1), + + // t6 *= t5; + c.call(ftmPrefix + "_mul", t6, t5, t6), + + // t6 = t6.frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap1", t6, t6), + + // t3 *= t0; + c.call(ftmPrefix + "_mul", t3, t0, t3), + + // t3 = t3.frobenius_map().frobenius_map(); + c.call(ftmPrefix + "_frobeniusMap2", t3, t3), + + // t3 *= t1; + c.call(ftmPrefix + "_mul", t3, t1, t3), + + // t3 *= t6; + c.call(ftmPrefix + "_mul", t3, t6, t3), + + // f = t3 * t4; + c.call(ftmPrefix + "_mul", t3, t4, res), + + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt("322277361516934140462891564586510139908379969514828494218366688025288661041104682794998680497580008899973249814104447692778988208376779573819485263026159588510513834876303014016798809919343532899164848730280942609956670917565618115867287399623286813270357901731510188149934363360381614501334086825442271920079363289954510565375378443704372994881406797882676971082200626541916413184642520269678897559532260949334760604962086348898118982248842634379637598665468817769075878555493752214492790122785850202957575200176084204422751485957336465472324810982833638490904279282696134323072515220044451592646885410572234451732790590013479358343841220074174848221722017083597872017638514103174122784843925578370430843522959600095676285723737049438346544753168912974976791528535276317256904336520179281145394686565050419250614107803233314658825463117900250701199181529205942363159325765991819433914303908860460720581408201373164047773794825411011922305820065611121544561808414055302212057471395719432072209245600258134364584636810093520285711072578721435517884103526483832733289802426157301542744476740008494780363354305116978805620671467071400711358839553375340724899735460480144599782014906586543813292157922220645089192130209334926661588737007768565838519456601560804957985667880395221049249803753582637708560"); + + const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 544 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(544), c.getLocal("r")), + ); + } + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i { + +const bigInt = __webpack_require__(2096); +const utils = __webpack_require__(2333); + +const buildF1m =__webpack_require__(75); +const buildF1 =__webpack_require__(8138); +const buildF2m =__webpack_require__(5420); +const buildF3m =__webpack_require__(7173); +const buildCurve =__webpack_require__(5904); +const buildFFT = __webpack_require__(3911); +const buildPol = __webpack_require__(2896); +const buildQAP = __webpack_require__(637); +const buildApplyKey = __webpack_require__(3320); + +module.exports = function buildBN128(module, _prefix) { + + const prefix = _prefix || "bn128"; + + if (module.modules[prefix]) return prefix; // already builded + + const q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"); + const r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + + + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + const frsize = n8; + const f1size = n8; + const f2size = f1size * 2; + const f6size = f1size * 6; + const ftsize = f1size * 12; + + const pr = module.alloc(utils.bigInt2BytesLE( r, frsize )); + + const f1mPrefix = buildF1m(module, q, "f1m"); + buildF1(module, r, "fr", "frm"); + + const pG1b = module.alloc(utils.bigInt2BytesLE( toMontgomery(bigInt(3)), f1size )); + const g1mPrefix = buildCurve(module, "g1m", "f1m", pG1b); + + buildFFT(module, "frm", "frm", "frm", "frm_mul"); + + buildPol(module, "pol", "frm"); + buildQAP(module, "qap", "frm"); + + const f2mPrefix = buildF2m(module, "f1m_neg", "f2m", "f1m"); + const pG2b = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(bigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373")), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(bigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")), f1size ) + ]); + const g2mPrefix = buildCurve(module, "g2m", "f2m", pG2b); + + + function buildGTimesFr(fnName, opMul) { + const f = module.addFunction(fnName); + f.addParam("pG", "i32"); + f.addParam("pFr", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call("frm_fromMontgomery", c.getLocal("pFr"), AUX), + c.call( + opMul, + c.getLocal("pG"), + AUX, + c.i32_const(n8), + c.getLocal("pr") + ) + ); + + module.exportFunction(fnName); + } + buildGTimesFr("g1m_timesFr", "g1m_timesScalar"); + buildFFT(module, "g1m", "g1m", "frm", "g1m_timesFr"); + + buildGTimesFr("g2m_timesFr", "g2m_timesScalar"); + buildFFT(module, "g2m", "g2m", "frm", "g2m_timesFr"); + + buildGTimesFr("g1m_timesFrAffine", "g1m_timesScalarAffine"); + buildGTimesFr("g2m_timesFrAffine", "g2m_timesScalarAffine"); + + buildApplyKey(module, "frm_batchApplyKey", "fmr", "frm", n8, n8, n8, "frm_mul"); + buildApplyKey(module, "g1m_batchApplyKey", "g1m", "frm", n8*3, n8*3, n8, "g1m_timesFr"); + buildApplyKey(module, "g1m_batchApplyKeyMixed", "g1m", "frm", n8*2, n8*3, n8, "g1m_timesFrAffine"); + buildApplyKey(module, "g2m_batchApplyKey", "g2m", "frm", n8*2*3, n8*3*2, n8, "g2m_timesFr"); + buildApplyKey(module, "g2m_batchApplyKeyMixed", "g2m", "frm", n8*2*2, n8*3*2, n8, "g2m_timesFrAffine"); + + function toMontgomery(a) { + return bigInt(a).times( bigInt.one.shiftLeft(f1size*8)).mod(q); + } + + const G1gen = [ + bigInt("1"), + bigInt("2"), + bigInt.one + ]; + + const pG1gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1gen[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1gen[2]), f1size ), + ] + ); + + const G1zero = [ + bigInt.zero, + bigInt.one, + bigInt.zero + ]; + + const pG1zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G1zero[0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G1zero[2]), f1size ) + ] + ); + + const G2gen = [ + [ + bigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"), + bigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634"), + ],[ + bigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"), + bigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531"), + ],[ + bigInt.one, + bigInt.zero, + ] + ]; + + const pG2gen = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2gen[2][1]), f1size ), + ] + ); + + const G2zero = [ + [ + bigInt.zero, + bigInt.zero, + ],[ + bigInt.one, + bigInt.zero, + ],[ + bigInt.zero, + bigInt.zero, + ] + ]; + + const pG2zero = module.alloc( + [ + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[0][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[1][1]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][0]), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(G2zero[2][1]), f1size ), + ] + ); + + const pOneT = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(0), f1size ), + ]); + + const pNonResidueF6 = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery(9), f1size ), + ...utils.bigInt2BytesLE( toMontgomery(1), f1size ), + ]); + + const pTwoInv = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery( bigInt(2).modInv(q)), f1size ), + ...utils.bigInt2BytesLE( bigInt(0), f1size ) + ]); + + const pAltBn128Twist = pNonResidueF6; + + const pTwistCoefB = module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("19485874751759354771024239261021720505790618469301721065564631296452457478373"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("266929791119991161246907387137283842545076965332900288569378510910307636690"), f1size ), + ]); + + function build_mulNR6() { + const f = module.addFunction(prefix + "_mulNR6"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.getLocal("x"), + c.getLocal("pr") + ) + ); + } + build_mulNR6(); + + const f6mPrefix = buildF3m(module, prefix+"_mulNR6", "f6m", "f2m"); + + function build_mulNR12() { + const f = module.addFunction(prefix + "_mulNR12"); + f.addParam("x", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call( + f2mPrefix + "_mul", + c.i32_const(pNonResidueF6), + c.i32_add(c.getLocal("x"), c.i32_const(n8*4)), + c.getLocal("pr") + ), + c.call( + f2mPrefix + "_copy", + c.getLocal("x"), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*2)), + ), + c.call( + f2mPrefix + "_copy", + c.i32_add(c.getLocal("x"), c.i32_const(n8*2)), + c.i32_add(c.getLocal("pr"), c.i32_const(n8*4)), + ) + ); + } + build_mulNR12(); + + const ftmPrefix = buildF2m(module, prefix+"_mulNR12", "ftm", f6mPrefix); + + + const ateLoopCount = bigInt("29793968203157093288"); + const ateLoopBitBytes = bits(ateLoopCount); + const pAteLoopBitBytes = module.alloc(ateLoopBitBytes); + const isLoopNegative = false; + + const ateCoefSize = 3 * f2size; + const ateNDblCoefs = ateLoopBitBytes.length-1; + const ateNAddCoefs = ateLoopBitBytes.reduce((acc, b) => acc + ( b!=0 ? 1 : 0) ,0); + const ateNCoefs = ateNAddCoefs + ateNDblCoefs + 1; + const prePSize = 3*2*n8; + const preQSize = 3*n8*2 + ateNCoefs*ateCoefSize; + const finalExpIsNegative = false; + + + module.modules[prefix] = { + n64: n64, + pG1gen: pG1gen, + pG1zero: pG1zero, + pG1b: pG1b, + pG2gen: pG2gen, + pG2zero: pG2zero, + pG2b: pG2b, + pq: module.modules["f1m"].pq, + pr: pr, + pOneT: pOneT, + prePSize: prePSize, + preQSize: preQSize, + r: r.toString(), + q: q.toString() + }; + + // console.log("PrePSize: " +prePSize); + // console.log("PreQSize: " +preQSize); + + const finalExpZ = bigInt("4965661367192848881"); + + function naf(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function bits(n) { + let E = n; + const res = []; + while (E.gt(bigInt.zero)) { + if (E.isOdd()) { + res.push( 1 ); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; + } + + function buildPrepareG1() { + const f = module.addFunction(prefix+ "_prepareG1"); + f.addParam("pP", "i32"); + f.addParam("ppreP", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(g1mPrefix + "_normalize", c.getLocal("pP"), c.getLocal("ppreP")), // TODO Remove if already in affine + ); + } + + function buildPrepAddStep() { + const f = module.addFunction(prefix+ "_prepAddStep"); + f.addParam("pQ", "i32"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X2 = c.getLocal("pQ"); + const Y2 = c.i32_add(c.getLocal("pQ"), c.i32_const(f2size)); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const D = ELL_VW; + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + // D = X1 - X2*Z1 + c.call(f2mPrefix + "_mul", X2, Z1, D), + c.call(f2mPrefix + "_sub", X1, D, D), + + // E = Y1 - Y2*Z1 + c.call(f2mPrefix + "_mul", Y2, Z1, E), + c.call(f2mPrefix + "_sub", Y1, E, E), + + // F = D^2 + c.call(f2mPrefix + "_square", D, F), + + // G = E^2 + c.call(f2mPrefix + "_square", E, G), + + // H = D*F + c.call(f2mPrefix + "_mul", D, F, H), + + // I = X1 * F + c.call(f2mPrefix + "_mul", X1, F, I), + + // J = H + Z1*G - (I+I) + c.call(f2mPrefix + "_add", I, I, AUX), + c.call(f2mPrefix + "_mul", Z1, G, J), + c.call(f2mPrefix + "_add", H, J, J), + c.call(f2mPrefix + "_sub", J, AUX, J), + + + // X3 (X1) = D*J + c.call(f2mPrefix + "_mul", D, J, X1), + + // Y3 (Y1) = E*(I-J)-(H*Y1) + c.call(f2mPrefix + "_mul", H, Y1, Y1), + c.call(f2mPrefix + "_sub", I, J, AUX), + c.call(f2mPrefix + "_mul", E, AUX, AUX), + c.call(f2mPrefix + "_sub", AUX, Y1, Y1), + + // Z3 (Z1) = Z1*H + c.call(f2mPrefix + "_mul", Z1, H, Z1), + + // ell_0 = xi * (E * X2 - D * Y2) + c.call(f2mPrefix + "_mul", D, Y2, AUX), + c.call(f2mPrefix + "_mul", E, X2, ELL_0), + c.call(f2mPrefix + "_sub", ELL_0, AUX, ELL_0), + c.call(f2mPrefix + "_mul", ELL_0, c.i32_const(pAltBn128Twist), ELL_0), + + + // ell_VV = - E (later: * xP) + c.call(f2mPrefix + "_neg", E, ELL_VV), + + // ell_VW = D (later: * yP ) + // Already assigned + + ); + } + + + + function buildPrepDoubleStep() { + const f = module.addFunction(prefix+ "_prepDblStep"); + f.addParam("pR", "i32"); + f.addParam("pCoef", "i32"); + + const c = f.getCodeBuilder(); + + const X1 = c.getLocal("pR"); + const Y1 = c.i32_add(c.getLocal("pR"), c.i32_const(f2size)); + const Z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*f2size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + const A = c.i32_const(module.alloc(f2size)); + const B = c.i32_const(module.alloc(f2size)); + const C = c.i32_const(module.alloc(f2size)); + const D = c.i32_const(module.alloc(f2size)); + const E = c.i32_const(module.alloc(f2size)); + const F = c.i32_const(module.alloc(f2size)); + const G = c.i32_const(module.alloc(f2size)); + const H = c.i32_const(module.alloc(f2size)); + const I = c.i32_const(module.alloc(f2size)); + const J = c.i32_const(module.alloc(f2size)); + const E2 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // A = X1 * Y1 / 2 + c.call(f2mPrefix + "_mul", Y1, c.i32_const(pTwoInv), A), + c.call(f2mPrefix + "_mul", X1, A, A), + + // B = Y1^2 + c.call(f2mPrefix + "_square", Y1, B), + + // C = Z1^2 + c.call(f2mPrefix + "_square", Z1, C), + + // D = 3 * C + c.call(f2mPrefix + "_add", C, C, D), + c.call(f2mPrefix + "_add", D, C, D), + + // E = twist_b * D + c.call(f2mPrefix + "_mul", c.i32_const(pTwistCoefB), D, E), + + // F = 3 * E + c.call(f2mPrefix + "_add", E, E, F), + c.call(f2mPrefix + "_add", E, F, F), + + // G = (B+F)/2 + c.call(f2mPrefix + "_add", B, F, G), + c.call(f2mPrefix + "_mul", G, c.i32_const(pTwoInv), G), + + // H = (Y1+Z1)^2-(B+C) + c.call(f2mPrefix + "_add", B, C, AUX), + c.call(f2mPrefix + "_add", Y1, Z1, H), + c.call(f2mPrefix + "_square", H, H), + c.call(f2mPrefix + "_sub", H, AUX, H), + + // I = E-B + c.call(f2mPrefix + "_sub", E, B, I), + + // J = X1^2 + c.call(f2mPrefix + "_square", X1, J), + + // E_squared = E^2 + c.call(f2mPrefix + "_square", E, E2), + + // X3 (X1) = A * (B-F) + c.call(f2mPrefix + "_sub", B, F, AUX), + c.call(f2mPrefix + "_mul", A, AUX, X1), + + // Y3 (Y1) = G^2 - 3*E^2 + c.call(f2mPrefix + "_add", E2, E2, AUX), + c.call(f2mPrefix + "_add", E2, AUX, AUX), + c.call(f2mPrefix + "_square", G, Y1), + c.call(f2mPrefix + "_sub", Y1, AUX, Y1), + + // Z3 (Z1) = B * H + c.call(f2mPrefix + "_mul", B, H, Z1), + + // ell_0 = xi * I + c.call(f2mPrefix + "_mul", c.i32_const(pAltBn128Twist), I, ELL_0), + + // ell_VW = - H (later: * yP) + c.call(f2mPrefix + "_neg", H, ELL_VW), + + // ell_VV = 3*J (later: * xP) + c.call(f2mPrefix + "_add", J, J, ELL_VV), + c.call(f2mPrefix + "_add", J, ELL_VV, ELL_VV), + + ); + } + + function buildMulByQ() { + const f = module.addFunction(prefix + "_mulByQ"); + f.addParam("p1", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("p1"); + const y = c.i32_add(c.getLocal("p1"), c.i32_const(f2size)); + const z = c.i32_add(c.getLocal("p1"), c.i32_const(f2size*2)); + const x3 = c.getLocal("pr"); + const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size)); + const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(f2size*2)); + + const MulByQX = c.i32_const(module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("21575463638280843010398324269430826099269044274347216827212613867836435027261"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("10307601595873709700152284273816112264069230130616436755625194854815875713954"), f1size ), + ])); + + const MulByQY = c.i32_const(module.alloc([ + ...utils.bigInt2BytesLE( toMontgomery("2821565182194536844548159561693502659359617185244120367078079554186484126554"), f1size ), + ...utils.bigInt2BytesLE( toMontgomery("3505843767911556378687030309984248845540243509899259641013678093033130930403"), f1size ), + ])); + + f.addCode( + // The frobeniusMap(1) in this field, is the conjugate + c.call(f2mPrefix + "_conjugate", x, x3), + c.call(f2mPrefix + "_mul", MulByQX, x3, x3), + c.call(f2mPrefix + "_conjugate", y, y3), + c.call(f2mPrefix + "_mul", MulByQY, y3, y3), + c.call(f2mPrefix + "_conjugate", z, z3), + ); + } + + + function buildPrepareG2() { + buildMulByQ(); + const f = module.addFunction(prefix+ "_prepareG2"); + f.addParam("pQ", "i32"); + f.addParam("ppreQ", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const QX = c.getLocal("pQ"); + const QY = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size)); + const QZ = c.i32_add( c.getLocal("pQ"), c.i32_const(f2size*2)); + + const pR = module.alloc(f2size*3); + const R = c.i32_const(pR); + const RX = c.i32_const(pR); + const RY = c.i32_const(pR+f2size); + const RZ = c.i32_const(pR+2*f2size); + + const cQX = c.i32_add( c.getLocal("ppreQ"), c.i32_const(0)); + const cQY = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size)); + const cQZ = c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*2)); + + const pQ1 = module.alloc(f2size*3); + const Q1 = c.i32_const(pQ1); + + const pQ2 = module.alloc(f2size*3); + const Q2 = c.i32_const(pQ2); + const Q2X = c.i32_const(pQ2); + const Q2Y = c.i32_const(pQ2 + f2size); + const Q2Z = c.i32_const(pQ2 + f2size*2); + + f.addCode( + c.call(g2mPrefix + "_normalize", QX, cQX), // TODO Remove if already in affine + c.call(f2mPrefix + "_copy", cQX, RX), + c.call(f2mPrefix + "_copy", cQY, RY), + c.call(f2mPrefix + "_one", RZ), + ); + + f.addCode( + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + c.call(prefix + "_prepDblStep", R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(prefix + "_prepAddStep", cQX, R, c.getLocal("pCoef")), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + f.addCode( + c.call(prefix + "_mulByQ", cQX, Q1), + c.call(prefix + "_mulByQ", Q1, Q2) + ); + + if (isLoopNegative) { + f.addCode( + c.call(f2mPrefix + "_neg", RY, RY), + ); + } + + f.addCode( + c.call(f2mPrefix + "_neg", Q2Y, Q2Y), + + c.call(prefix + "_prepAddStep", Q1, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(prefix + "_prepAddStep", Q2, R, c.getLocal("pCoef")), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + ); + } + + function buildMulBy024Old() { + const f = module.addFunction(prefix+ "__mulBy024Old"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + + const pAUX12 = module.alloc(ftsize); + const AUX12 = c.i32_const(pAUX12); + const AUX12_0 = c.i32_const(pAUX12); + const AUX12_2 = c.i32_const(pAUX12+f2size); + const AUX12_4 = c.i32_const(pAUX12+f2size*2); + const AUX12_6 = c.i32_const(pAUX12+f2size*3); + const AUX12_8 = c.i32_const(pAUX12+f2size*4); + const AUX12_10 = c.i32_const(pAUX12+f2size*5); + + f.addCode( + + c.call(f2mPrefix + "_copy", x0, AUX12_0), + c.call(f2mPrefix + "_zero", AUX12_2), + c.call(f2mPrefix + "_copy", x2, AUX12_4), + c.call(f2mPrefix + "_zero", AUX12_6), + c.call(f2mPrefix + "_copy", x4, AUX12_8), + c.call(f2mPrefix + "_zero", AUX12_10), + c.call(ftmPrefix + "_mul", AUX12, z0, z0), + ); + } + + function buildMulBy024() { + const f = module.addFunction(prefix+ "__mulBy024"); + f.addParam("pEll0", "i32"); + f.addParam("pEllVW", "i32"); + f.addParam("pEllVV", "i32"); + f.addParam("pR", "i32"); // Result in F12 + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("pEll0"); + const x2 = c.getLocal("pEllVV"); + const x4 = c.getLocal("pEllVW"); + + const z0 = c.getLocal("pR"); + const z1 = c.i32_add(c.getLocal("pR"), c.i32_const(2*n8)); + const z2 = c.i32_add(c.getLocal("pR"), c.i32_const(4*n8)); + const z3 = c.i32_add(c.getLocal("pR"), c.i32_const(6*n8)); + const z4 = c.i32_add(c.getLocal("pR"), c.i32_const(8*n8)); + const z5 = c.i32_add(c.getLocal("pR"), c.i32_const(10*n8)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const s0 = c.i32_const(module.alloc(f2size)); + const T3 = c.i32_const(module.alloc(f2size)); + const T4 = c.i32_const(module.alloc(f2size)); + const D0 = c.i32_const(module.alloc(f2size)); + const D2 = c.i32_const(module.alloc(f2size)); + const D4 = c.i32_const(module.alloc(f2size)); + const S1 = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + f.addCode( + + // D0 = z0 * x0; + c.call(f2mPrefix + "_mul", z0, x0, D0), + // D2 = z2 * x2; + c.call(f2mPrefix + "_mul", z2, x2, D2), + // D4 = z4 * x4; + c.call(f2mPrefix + "_mul", z4, x4, D4), + // t2 = z0 + z4; + c.call(f2mPrefix + "_add", z0, z4, t2), + // t1 = z0 + z2; + c.call(f2mPrefix + "_add", z0, z2, t1), + // s0 = z1 + z3 + z5; + c.call(f2mPrefix + "_add", z1, z3, s0), + c.call(f2mPrefix + "_add", s0, z5, s0), + + + // For z.a_.a_ = z0. + // S1 = z1 * x2; + c.call(f2mPrefix + "_mul", z1, x2, S1), + // T3 = S1 + D4; + c.call(f2mPrefix + "_add", S1, D4, T3), + // T4 = my_Fp6::non_residue * T3 + D0; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + c.call(f2mPrefix + "_add", T4, D0, z0), + // z0 = T4; + + // For z.a_.b_ = z1 + // T3 = z5 * x4; + c.call(f2mPrefix + "_mul", z5, x4, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T3 = T3 + D2; + c.call(f2mPrefix + "_add", T3, D2, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z1 * x0; + c.call(f2mPrefix + "_mul", z1, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z1), + // z1 = T4; + + + + // For z.a_.c_ = z2 + // t0 = x0 + x2; + c.call(f2mPrefix + "_add", x0, x2, t0), + // T3 = t1 * t0 - D0 - D2; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D0, D2, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = z3 * x4; + c.call(f2mPrefix + "_mul", z3, x4, T4), + // S1 = S1 + T4; + c.call(f2mPrefix + "_add", S1, T4, S1), + + + // For z.b_.a_ = z3 (z3 needs z2) + // t0 = z2 + z4; + c.call(f2mPrefix + "_add", z2, z4, t0), + // T3 = T3 + T4; + // z2 = T3; + c.call(f2mPrefix + "_add", T3, T4, z2), + // t1 = x2 + x4; + c.call(f2mPrefix + "_add", x2, x4, t1), + // T3 = t0 * t1 - D2 - D4; + c.call(f2mPrefix + "_mul", t1, t0, T3), + c.call(f2mPrefix + "_add", D2, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // T3 = z3 * x0; + c.call(f2mPrefix + "_mul", z3, x0, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z3), + // z3 = T4; + + // For z.b_.b_ = z4 + // T3 = z5 * x2; + c.call(f2mPrefix + "_mul", z5, x2, T3), + // S1 = S1 + T3; + c.call(f2mPrefix + "_add", S1, T3, S1), + // T4 = my_Fp6::non_residue * T3; + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), T3, T4), + // t0 = x0 + x4; + c.call(f2mPrefix + "_add", x0, x4, t0), + // T3 = t2 * t0 - D0 - D4; + c.call(f2mPrefix + "_mul", t2, t0, T3), + c.call(f2mPrefix + "_add", D0, D4, AUX), + c.call(f2mPrefix + "_sub", T3, AUX, T3), + // T4 = T4 + T3; + c.call(f2mPrefix + "_add", T4, T3, z4), + // z4 = T4; + + // For z.b_.c_ = z5. + // t0 = x0 + x2 + x4; + c.call(f2mPrefix + "_add", x0, x2, t0), + c.call(f2mPrefix + "_add", t0, x4, t0), + // T3 = s0 * t0 - S1; + c.call(f2mPrefix + "_mul", s0, t0, T3), + c.call(f2mPrefix + "_sub", T3, S1, z5), + // z5 = T3; + + ); + } + + + function buildMillerLoop() { + const f = module.addFunction(prefix+ "_millerLoop"); + f.addParam("ppreP", "i32"); + f.addParam("ppreQ", "i32"); + f.addParam("r", "i32"); + f.addLocal("pCoef", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const preP_PX = c.getLocal("ppreP"); + const preP_PY = c.i32_add(c.getLocal("ppreP"), c.i32_const(f1size)); + + const ELL_0 = c.getLocal("pCoef"); + const ELL_VW = c.i32_add(c.getLocal("pCoef"), c.i32_const(f2size)); + const ELL_VV = c.i32_add(c.getLocal("pCoef"), c.i32_const(2*f2size)); + + + const pVW = module.alloc(f2size); + const VW = c.i32_const(pVW); + const pVV = module.alloc(f2size); + const VV = c.i32_const(pVV); + + const F = c.getLocal("r"); + + + f.addCode( + c.call(ftmPrefix + "_one", F), + + c.setLocal("pCoef", c.i32_add( c.getLocal("ppreQ"), c.i32_const(f2size*3))), + + c.setLocal("i", c.i32_const(ateLoopBitBytes.length-2)), + c.block(c.loop( + + + c.call(ftmPrefix + "_square", F, F), + + c.call(f2mPrefix + "_mul1", ELL_VW,preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.if( + c.i32_load8_s(c.getLocal("i"), pAteLoopBitBytes), + [ + ...c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + ...c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + + ...c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + ...c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ] + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + + ); + + if (isLoopNegative) { + f.addCode( + c.call(ftmPrefix + "_inverse", F, F), + ); + } + + f.addCode( + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + c.call(f2mPrefix + "_mul1", ELL_VW, preP_PY, VW), + c.call(f2mPrefix + "_mul1", ELL_VV, preP_PX, VV), + c.call(prefix + "__mulBy024", ELL_0, VW, VV, F), + c.setLocal("pCoef", c.i32_add(c.getLocal("pCoef"), c.i32_const(ateCoefSize))), + + ); + + } + + + function buildFrobeniusMap(n) { + const F12 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("8376118865763821496583973867626364092589906065868298776909617916018768340080"), bigInt("16469823323077808223889137241176536799009286646108169935659301613961712198316")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556617"), bigInt("0")], + [bigInt("11697423496358154304825782922584725312912383441159505038794027105778954184319"), bigInt("303847389135065887422783454877609941456349188919719272345083954437860409601")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("3321304630594332808241809054958361220322477375291206261884409189760185844239"), bigInt("5722266937896532885780051958958348231143373700109372999374820235121374419868")], + [bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582"), bigInt("0")], + [bigInt("13512124006075453725662431877630910996106405091429524885779419978626457868503"), bigInt("5418419548761466998357268504080738289687024511189653727029736280683514010267")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("10190819375481120917420622822672549775783927716138318623895010788866272024264"), bigInt("21584395482704209334823622290379665147239961968378104390343953940207365798982")], + [bigInt("2203960485148121921418603742825762020974279258880205651967"), bigInt("0")], + [bigInt("18566938241244942414004596690298913868373833782006617400804628704885040364344"), bigInt("16165975933942742336466353786298926857552937457188450663314217659523851788715")], + ] + ]; + + const F6 = [ + [ + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + [bigInt("1"), bigInt("0")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("21575463638280843010398324269430826099269044274347216827212613867836435027261"), bigInt("10307601595873709700152284273816112264069230130616436755625194854815875713954")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("3772000881919853776433695186713858239009073593817195771773381919316419345261"), bigInt("2236595495967245188281701248203181795121068902605861227855261137820944008926")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("18429021223477853657660792034369865839114504446431234726392080002137598044644"), bigInt("9344045779998320333812420223237981029506012124075525679208581902008406485703")], + ], + [ + [bigInt("1"), bigInt("0")], + [bigInt("2581911344467009335267311115468803099551665605076196740867805258568234346338"), bigInt("19937756971775647987995932169929341994314640652964949448313374472400716661030")], + [bigInt("2203960485148121921418603742825762020974279258880205651966"), bigInt("0")], + [bigInt("5324479202449903542726783395506214481928257762400643279780343368557297135718"), bigInt("16208900380737693084919495127334387981393726419856888799917914180988844123039")], + [bigInt("21888242871839275220042445260109153167277707414472061641714758635765020556616"), bigInt("0")], + [bigInt("13981852324922362344252311234282257507216387789820983642040889267519694726527"), bigInt("7629828391165209371577384193250820201684255241773809077146787135900891633097")], + ] + ]; + + const f = module.addFunction(prefix+ "__frobeniusMap"+n); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i<6; i++) { + const X = (i==0) ? c.getLocal("x") : c.i32_add(c.getLocal("x"), c.i32_const(i*f2size)); + const Xc0 = X; + const Xc1 = c.i32_add(c.getLocal("x"), c.i32_const(i*f2size + f1size)); + const R = (i==0) ? c.getLocal("r") : c.i32_add(c.getLocal("r"), c.i32_const(i*f2size)); + const Rc0 = R; + const Rc1 = c.i32_add(c.getLocal("r"), c.i32_const(i*f2size + f1size)); + const coef = mul2(F12[Math.floor(i/3)][n%12] , F6[i%3][n%6]); + const pCoef = module.alloc([ + ...utils.bigInt2BytesLE(toMontgomery(coef[0]), 32), + ...utils.bigInt2BytesLE(toMontgomery(coef[1]), 32), + ]); + if (n%2 == 1) { + f.addCode( + c.call(f1mPrefix + "_copy", Xc0, Rc0), + c.call(f1mPrefix + "_neg", Xc1, Rc1), + c.call(f2mPrefix + "_mul", R, c.i32_const(pCoef), R), + ); + } else { + f.addCode(c.call(f2mPrefix + "_mul", X, c.i32_const(pCoef), R)); + } + } + + function mul2(a, b) { + const ac0 = bigInt(a[0]); + const ac1 = bigInt(a[1]); + const bc0 = bigInt(b[0]); + const bc1 = bigInt(b[1]); + const res = [ + ac0.times(bc0).minus( ac1.times(bc1) ).mod(q), + ac0.times(bc1).add( ac1.times(bc0) ).mod(q), + ]; + if (res[0].isNegative()) res[0] = res[0].add(q); + return res; + } + + } + + + + function buildFinalExponentiationFirstChunk() { + + const f = module.addFunction(prefix+ "__finalExponentiationFirstChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const eltC0 = elt; + const eltC1 = c.i32_add(elt, c.i32_const(n8*6)); + const r = c.getLocal("r"); + const pA = module.alloc(ftsize); + const A = c.i32_const(pA); + const Ac0 = A; + const Ac1 = c.i32_const(pA + n8*6); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + + f.addCode( + // const alt_bn128_Fq12 A = alt_bn128_Fq12(elt.c0,-elt.c1); + c.call(f6mPrefix + "_copy", eltC0, Ac0), + c.call(f6mPrefix + "_neg", eltC1, Ac1), + + // const alt_bn128_Fq12 B = elt.inverse(); + c.call(ftmPrefix + "_inverse", elt, B), + + // const alt_bn128_Fq12 C = A * B; + c.call(ftmPrefix + "_mul", A, B, C), + // const alt_bn128_Fq12 D = C.Frobenius_map(2); + c.call(prefix + "__frobeniusMap2", C, D), + // const alt_bn128_Fq12 result = D * C; + c.call(ftmPrefix + "_mul", C, D, r), + ); + } + + function buildCyclotomicSquare() { + const f = module.addFunction(prefix+ "__cyclotomicSquare"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x4 = c.i32_add(c.getLocal("x"), c.i32_const(f2size)); + const x3 = c.i32_add(c.getLocal("x"), c.i32_const(2*f2size)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(3*f2size)); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(4*f2size)); + const x5 = c.i32_add(c.getLocal("x"), c.i32_const(5*f2size)); + + const r0 = c.getLocal("r"); + const r4 = c.i32_add(c.getLocal("r"), c.i32_const(f2size)); + const r3 = c.i32_add(c.getLocal("r"), c.i32_const(2*f2size)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(3*f2size)); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(4*f2size)); + const r5 = c.i32_add(c.getLocal("r"), c.i32_const(5*f2size)); + + const t0 = c.i32_const(module.alloc(f2size)); + const t1 = c.i32_const(module.alloc(f2size)); + const t2 = c.i32_const(module.alloc(f2size)); + const t3 = c.i32_const(module.alloc(f2size)); + const t4 = c.i32_const(module.alloc(f2size)); + const t5 = c.i32_const(module.alloc(f2size)); + const tmp = c.i32_const(module.alloc(f2size)); + const AUX = c.i32_const(module.alloc(f2size)); + + + f.addCode( + +// c.call(ftmPrefix + "_square", x0, r0), + + // // t0 + t1*y = (z0 + z1*y)^2 = a^2 + // tmp = z0 * z1; + // t0 = (z0 + z1) * (z0 + my_Fp6::non_residue * z1) - tmp - my_Fp6::non_residue * tmp; + // t1 = tmp + tmp; + c.call(f2mPrefix + "_mul", x0, x1, tmp), + c.call(f2mPrefix + "_mul", x1, c.i32_const(pNonResidueF6), t0), + c.call(f2mPrefix + "_add", x0, t0, t0), + c.call(f2mPrefix + "_add", x0, x1, AUX), + c.call(f2mPrefix + "_mul", AUX, t0, t0), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t0, AUX, t0), + c.call(f2mPrefix + "_add", tmp, tmp, t1), + + // // t2 + t3*y = (z2 + z3*y)^2 = b^2 + // tmp = z2 * z3; + // t2 = (z2 + z3) * (z2 + my_Fp6::non_residue * z3) - tmp - my_Fp6::non_residue * tmp; + // t3 = tmp + tmp; + c.call(f2mPrefix + "_mul", x2, x3, tmp), + c.call(f2mPrefix + "_mul", x3, c.i32_const(pNonResidueF6), t2), + c.call(f2mPrefix + "_add", x2, t2, t2), + c.call(f2mPrefix + "_add", x2, x3, AUX), + c.call(f2mPrefix + "_mul", AUX, t2, t2), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t2, AUX, t2), + c.call(f2mPrefix + "_add", tmp, tmp, t3), + + // // t4 + t5*y = (z4 + z5*y)^2 = c^2 + // tmp = z4 * z5; + // t4 = (z4 + z5) * (z4 + my_Fp6::non_residue * z5) - tmp - my_Fp6::non_residue * tmp; + // t5 = tmp + tmp; + c.call(f2mPrefix + "_mul", x4, x5, tmp), + c.call(f2mPrefix + "_mul", x5, c.i32_const(pNonResidueF6), t4), + c.call(f2mPrefix + "_add", x4, t4, t4), + c.call(f2mPrefix + "_add", x4, x5, AUX), + c.call(f2mPrefix + "_mul", AUX, t4, t4), + c.call(f2mPrefix + "_mul", c.i32_const(pNonResidueF6), tmp, AUX), + c.call(f2mPrefix + "_add", tmp, AUX, AUX), + c.call(f2mPrefix + "_sub", t4, AUX, t4), + c.call(f2mPrefix + "_add", tmp, tmp, t5), + + // For A + // z0 = 3 * t0 - 2 * z0 + c.call(f2mPrefix + "_sub", t0, x0, r0), + c.call(f2mPrefix + "_add", r0, r0, r0), + c.call(f2mPrefix + "_add", t0, r0, r0), + // z1 = 3 * t1 + 2 * z1 + c.call(f2mPrefix + "_add", t1, x1, r1), + c.call(f2mPrefix + "_add", r1, r1, r1), + c.call(f2mPrefix + "_add", t1, r1, r1), + + // For B + // z2 = 3 * (xi * t5) + 2 * z2 + c.call(f2mPrefix + "_mul", t5, c.i32_const(pAltBn128Twist), AUX), + c.call(f2mPrefix + "_add", AUX, x2, r2), + c.call(f2mPrefix + "_add", r2, r2, r2), + c.call(f2mPrefix + "_add", AUX, r2, r2), + // z3 = 3 * t4 - 2 * z3 + c.call(f2mPrefix + "_sub", t4, x3, r3), + c.call(f2mPrefix + "_add", r3, r3, r3), + c.call(f2mPrefix + "_add", t4, r3, r3), + + // For C + // z4 = 3 * t2 - 2 * z4 + c.call(f2mPrefix + "_sub", t2, x4, r4), + c.call(f2mPrefix + "_add", r4, r4, r4), + c.call(f2mPrefix + "_add", t2, r4, r4), + // z5 = 3 * t3 + 2 * z5 + c.call(f2mPrefix + "_add", t3, x5, r5), + c.call(f2mPrefix + "_add", r5, r5, r5), + c.call(f2mPrefix + "_add", t3, r5, r5), + + ); + } + + + function buildCyclotomicExp(exponent, fnName) { + const exponentNafBytes = naf(exponent).map( (b) => (b==-1 ? 0xFF: b) ); + const pExponentNafBytes = module.alloc(exponentNafBytes); + const pExponent = module.alloc(utils.bigInt2BytesLE(exponent, 32)); + + const f = module.addFunction(prefix+ "__cyclotomicExp_"+fnName); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("bit", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const x = c.getLocal("x"); + + const res = c.getLocal("r"); + + const inverse = c.i32_const(module.alloc(ftsize)); + + + f.addCode( +// c.call(ftmPrefix + "_exp", x, c.i32_const(pExponent), c.i32_const(32), res), + + c.call(ftmPrefix + "_conjugate", x, inverse), + c.call(ftmPrefix + "_one", res), + + c.if( + c.teeLocal("bit", c.i32_load8_s(c.i32_const(exponentNafBytes.length-1), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + + c.setLocal("i", c.i32_const(exponentNafBytes.length-2)), + c.block(c.loop( +// c.call(ftmPrefix + "_square", res, res), + c.call(prefix + "__cyclotomicSquare", res, res), + c.if( + c.teeLocal("bit", c.i32_load8_s(c.getLocal("i"), pExponentNafBytes)), + c.if( + c.i32_eq( + c.getLocal("bit"), + c.i32_const(1) + ), + c.call(ftmPrefix + "_mul", res, x, res), + c.call(ftmPrefix + "_mul", res, inverse, res), + ) + ), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildFinalExponentiationLastChunk() { + buildCyclotomicSquare(); + buildCyclotomicExp(finalExpZ, "w0"); + + const f = module.addFunction(prefix+ "__finalExponentiationLastChunk"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const A = c.i32_const(module.alloc(ftsize)); + const B = c.i32_const(module.alloc(ftsize)); + const C = c.i32_const(module.alloc(ftsize)); + const D = c.i32_const(module.alloc(ftsize)); + const E = c.i32_const(module.alloc(ftsize)); + const F = c.i32_const(module.alloc(ftsize)); + const G = c.i32_const(module.alloc(ftsize)); + const H = c.i32_const(module.alloc(ftsize)); + const I = c.i32_const(module.alloc(ftsize)); + const J = c.i32_const(module.alloc(ftsize)); + const K = c.i32_const(module.alloc(ftsize)); + const L = c.i32_const(module.alloc(ftsize)); + const M = c.i32_const(module.alloc(ftsize)); + const N = c.i32_const(module.alloc(ftsize)); + const O = c.i32_const(module.alloc(ftsize)); + const P = c.i32_const(module.alloc(ftsize)); + const Q = c.i32_const(module.alloc(ftsize)); + const R = c.i32_const(module.alloc(ftsize)); + const S = c.i32_const(module.alloc(ftsize)); + const T = c.i32_const(module.alloc(ftsize)); + const U = c.i32_const(module.alloc(ftsize)); + + f.addCode( + + + // A = exp_by_neg_z(elt) // = elt^(-z) + c.call(prefix + "__cyclotomicExp_w0", elt, A), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", A, A), + // B = A^2 // = elt^(-2*z) + c.call(prefix + "__cyclotomicSquare", A, B), + // C = B^2 // = elt^(-4*z) + c.call(prefix + "__cyclotomicSquare", B, C), + // D = C * B // = elt^(-6*z) + c.call(ftmPrefix + "_mul", C, B, D), + // E = exp_by_neg_z(D) // = elt^(6*z^2) + c.call(prefix + "__cyclotomicExp_w0", D, E), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", E, E), + // F = E^2 // = elt^(12*z^2) + c.call(prefix + "__cyclotomicSquare", E, F), + // G = epx_by_neg_z(F) // = elt^(-12*z^3) + c.call(prefix + "__cyclotomicExp_w0", F, G), + finalExpIsNegative ? [] : c.call(ftmPrefix + "_conjugate", G, G), + // H = conj(D) // = elt^(6*z) + c.call(ftmPrefix + "_conjugate", D, H), + // I = conj(G) // = elt^(12*z^3) + c.call(ftmPrefix + "_conjugate", G, I), + // J = I * E // = elt^(12*z^3 + 6*z^2) + c.call(ftmPrefix + "_mul", I, E, J), + // K = J * H // = elt^(12*z^3 + 6*z^2 + 6*z) + c.call(ftmPrefix + "_mul", J, H, K), + // L = K * B // = elt^(12*z^3 + 6*z^2 + 4*z) + c.call(ftmPrefix + "_mul", K, B, L), + // M = K * E // = elt^(12*z^3 + 12*z^2 + 6*z) + c.call(ftmPrefix + "_mul", K, E, M), + + // N = M * elt // = elt^(12*z^3 + 12*z^2 + 6*z + 1) + c.call(ftmPrefix + "_mul", M, elt, N), + + // O = L.Frobenius_map(1) // = elt^(q*(12*z^3 + 6*z^2 + 4*z)) + c.call(prefix + "__frobeniusMap1", L, O), + // P = O * N // = elt^(q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", O, N, P), + // Q = K.Frobenius_map(2) // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z)) + c.call(prefix + "__frobeniusMap2", K, Q), + // R = Q * P // = elt^(q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", Q, P, R), + // S = conj(elt) // = elt^(-1) + c.call(ftmPrefix + "_conjugate", elt, S), + // T = S * L // = elt^(12*z^3 + 6*z^2 + 4*z - 1) + c.call(ftmPrefix + "_mul", S, L, T), + // U = T.Frobenius_map(3) // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1)) + c.call(prefix + "__frobeniusMap3", T, U), + // V = U * R // = elt^(q^3(12*z^3 + 6*z^2 + 4*z - 1) + q^2 * (12*z^3 + 6*z^2 + 6*z) + q*(12*z^3 + 6*z^2 + 4*z) * (12*z^3 + 12*z^2 + 6*z + 1)) + c.call(ftmPrefix + "_mul", U, R, result), + // result = V + ); + } + + + function buildFinalExponentiation() { + buildFinalExponentiationFirstChunk(); + buildFinalExponentiationLastChunk(); + const f = module.addFunction(prefix+ "_finalExponentiation"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const elt = c.getLocal("x"); + const result = c.getLocal("r"); + const eltToFirstChunk = c.i32_const(module.alloc(ftsize)); + + f.addCode( + c.call(prefix + "__finalExponentiationFirstChunk", elt, eltToFirstChunk ), + c.call(prefix + "__finalExponentiationLastChunk", eltToFirstChunk, result ) + ); + } + + + function buildFinalExponentiationOld() { + const f = module.addFunction(prefix+ "_finalExponentiationOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const exponent = bigInt("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480"); + + const pExponent = module.alloc(utils.bigInt2BytesLE( exponent, 352 )); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(ftmPrefix + "_exp", c.getLocal("x"), c.i32_const(pExponent), c.i32_const(352), c.getLocal("r")), + ); + } + + + + + const pPreP = module.alloc(prePSize); + const pPreQ = module.alloc(preQSize); + + function buildPairingEquation(nPairings) { + + const f = module.addFunction(prefix+ "_pairingEq"+nPairings); + for (let i=0; i { + + + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildApplyKey(module, fnName, gPrefix, frPrefix, sizeGIn, sizeGOut, sizeF, opGtimesF) { + + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pFirst", "i32"); + f.addParam("pInc", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("pOldFree", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pFrom", "i32"); + f.addLocal("pTo", "i32"); + + const c = f.getCodeBuilder(); + + const t = c.i32_const(module.alloc(sizeF)); + + f.addCode( + c.setLocal("pFrom", c.getLocal("pIn")), + c.setLocal("pTo", c.getLocal("pOut")), + ); + + // t = first + f.addCode( + c.call( + frPrefix + "_copy", + c.getLocal("pFirst"), + t + ) + ); + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call( + opGtimesF, + c.getLocal("pFrom"), + t, + c.getLocal("pTo") + ), + c.setLocal("pFrom", c.i32_add(c.getLocal("pFrom"), c.i32_const(sizeGIn))), + c.setLocal("pTo", c.i32_add(c.getLocal("pTo"), c.i32_const(sizeGOut))), + + // t = t* inc + c.call( + frPrefix + "_mul", + t, + c.getLocal("pInc"), + t + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + module.exportFunction(fnName); + +}; + + +/***/ }), + +/***/ 9440: +/***/ ((module) => { + + + +module.exports = buildBatchConvertion; + +function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } + + const f = module.addFunction(fnName); + f.addParam("pIn", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut", "i32"); + + const c = f.getCodeBuilder(); + + if (reverse) { + f.addCode( + c.setLocal("itIn", + c.i32_add( + c.getLocal("pIn"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_sub(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn", c.getLocal("pIn")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn"), c.getLocal("itOut")), + + c.setLocal("itIn", c.i32_add(c.getLocal("itIn"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + + +/***/ }), + +/***/ 8163: +/***/ ((module) => { + + +module.exports = buildBatchInverse; + +function buildBatchInverse(module, prefix) { + + + const n8 = module.modules[prefix].n64*8; + + const f = module.addFunction(prefix+"_batchInverse"); + f.addParam("pIn", "i32"); + f.addParam("inStep", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addParam("outStep", "i32"); + f.addLocal("itAux", "i32"); + f.addLocal("itIn", "i32"); + f.addLocal("itOut","i32"); + f.addLocal("i","i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + + // Alloc Working space for accumulated umltiplications + f.addCode( + c.setLocal("itAux", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("itAux"), + c.i32_mul( + c.i32_add( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(n8) + ) + ) + ) + ); + + f.addCode( + + // aux[0] = a; + c.call(prefix+"_one", c.getLocal("itAux")), + // for (i=0;i { + + + +module.exports = buildBatchConvertion; + +function buildBatchConvertion(module, fnName, internalFnName, sizeIn, sizeOut, reverse) { + if (typeof reverse === "undefined") { + // Set the reverse in a way that allows to use the same buffer as in/out. + if (sizeIn < sizeOut) { + reverse = true; + } else { + reverse = false; + } + } + + const f = module.addFunction(fnName); + f.addParam("pIn1", "i32"); + f.addParam("pIn2", "i32"); + f.addParam("n", "i32"); + f.addParam("pOut", "i32"); + f.addLocal("i", "i32"); + f.addLocal("itIn1", "i32"); + f.addLocal("itIn2", "i32"); + f.addLocal("itOut", "i32"); + + const c = f.getCodeBuilder(); + + if (reverse) { + f.addCode( + c.setLocal("itIn1", + c.i32_add( + c.getLocal("pIn1"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itIn2", + c.i32_add( + c.getLocal("pIn2"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeIn) + ) + ) + ), + c.setLocal("itOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.i32_const(sizeOut) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn1"), c.getLocal("itIn2"), c.getLocal("itOut")), + + c.setLocal("itIn1", c.i32_sub(c.getLocal("itIn1"), c.i32_const(sizeIn))), + c.setLocal("itIn2", c.i32_sub(c.getLocal("itIn2"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_sub(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } else { + f.addCode( + c.setLocal("itIn1", c.getLocal("pIn1")), + c.setLocal("itIn2", c.getLocal("pIn2")), + c.setLocal("itOut", c.getLocal("pOut")), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq ( c.getLocal("i"), c.getLocal("n") )), + + c.call(internalFnName, c.getLocal("itIn1"), c.getLocal("itIn2"), c.getLocal("itOut")), + + c.setLocal("itIn1", c.i32_add(c.getLocal("itIn1"), c.i32_const(sizeIn))), + c.setLocal("itIn2", c.i32_add(c.getLocal("itIn2"), c.i32_const(sizeIn))), + c.setLocal("itOut", c.i32_add(c.getLocal("itOut"), c.i32_const(sizeOut))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + ); + } +} + + +/***/ }), + +/***/ 5904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const buildTimesScalarNAF = __webpack_require__(3972); +//const buildTimesScalar = require("./build_timesscalar"); +const buildBatchConvertion = __webpack_require__(9440); +const buildMultiexp = __webpack_require__(4911); + +module.exports = function buildCurve(module, prefix, prefixField, pB) { + + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64*3 + }; + + function buildIsZero() { + const f = module.addFunction(prefix + "_isZero"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8*2) + ) + )); + } + function buildIsZeroAffine() { + const f = module.addFunction(prefix + "_isZeroAffine"); + f.addParam("p1", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_and( + c.call( + prefixField + "_isZero", + c.getLocal("p1") + ), + c.call( + prefixField + "_isZero", + c.i32_add( + c.getLocal("p1"), + c.i32_const(n8) + ) + ) + ) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix + "_copy"); + f.addParam("ps", "i32"); + f.addParam("pd", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(2096); + +const buildF1m =__webpack_require__(75); + +module.exports = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) { + + const q = bigInt(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n8 = n64*8; + + const prefix = _prefix || "f1"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = { + n64: n64 + }; + + const intPrefix = _intPrefix || "int"; + const f1mPrefix = buildF1m(module, q, _f1mPrefix, intPrefix); + + + const pR2 = module.modules[f1mPrefix].pR2; + const pq = module.modules[f1mPrefix].pq; + const pePlusOne = module.modules[f1mPrefix].pePlusOne; + + function buildMul() { + const pAux1 = module.alloc(n8); + + const f = module.addFunction(prefix+ "_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1))); + f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r"))); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(intPrefix + "_gte", c.getLocal("x"), c.i32_const(pePlusOne) ) + ); + } + + + buildMul(); + buildSquare(); + buildInverse(); + buildIsNegative(); + module.exportFunction(f1mPrefix + "_add", prefix + "_add"); + module.exportFunction(f1mPrefix + "_sub", prefix + "_sub"); + module.exportFunction(f1mPrefix + "_neg", prefix + "_neg"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(f1mPrefix + "_copy", prefix+"_copy"); + module.exportFunction(f1mPrefix + "_zero", prefix+"_zero"); + module.exportFunction(f1mPrefix + "_one", prefix+"_one"); + module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(f1mPrefix + "_eq", prefix+"_eq"); + + return prefix; +}; + + +/***/ }), + +/***/ 75: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(2096); +const buildInt = __webpack_require__(6754); +const utils = __webpack_require__(2333); +const buildExp = __webpack_require__(5107); +const buildBatchInverse = __webpack_require__(8163); +const buildBatchConvertion = __webpack_require__(9440); +const buildBatchOp = __webpack_require__(4948); + +module.exports = function buildF1m(module, _q, _prefix, _intPrefix) { + const q = bigInt(_q); + const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1; + const n32 = n64*2; + const n8 = n64*8; + + const prefix = _prefix || "f1m"; + if (module.modules[prefix]) return prefix; // already builded + + const intPrefix = buildInt(module, n64, _intPrefix); + const pq = module.alloc(n8, utils.bigInt2BytesLE(q, n8)); + + const pR = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); + const pR2 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).square().mod(q), n8)); + const pOne = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8)); + const pZero = module.alloc(utils.bigInt2BytesLE(bigInt.zero, n8)); + const _minusOne = q.minus(bigInt.one); + const _e = _minusOne.shiftRight(1); // e = (p-1)/2 + const pe = module.alloc(n8, utils.bigInt2BytesLE(_e, n8)); + + const _ePlusOne = _e.add(bigInt.one); // e = (p-1)/2 + const pePlusOne = module.alloc(n8, utils.bigInt2BytesLE(_ePlusOne, n8)); + + module.modules[prefix] = { + pq: pq, + pR2: pR2, + n64: n64, + q: q, + pOne: pOne, + pZero: pZero, + pePlusOne: pePlusOne + }; + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(intPrefix + "_copy", c.i32_const(pOne), c.getLocal("pr"))); + } + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")), + c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))) + ) + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.call(prefix + "_sub", c.i32_const(pZero), c.getLocal("x"), c.getLocal("r")) + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne) ) + ); + } + + +/* + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.i32_and( + c.i32_load(AUX), + c.i32_const(1) + ) + ); + } +*/ + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if ( + c.call(intPrefix + "_isZero", c.getLocal("x")), + c.ret(c.i32_const(0)) + ), + c.call(prefix + "_fromMontgomery", c.getLocal("x"), AUX), + c.if( + c.call(intPrefix + "_gte", AUX, c.i32_const(pePlusOne)), + c.ret(c.i32_const(-1)) + ), + c.ret(c.i32_const(1)) + ); + } + + + function buildMReduct() { + const carries = module.alloc(n32*n32*8); + + const f = module.addFunction(prefix+"_mReduct"); + f.addParam("t", "i32"); + f.addParam("r", "i32"); + f.addLocal("np32", "i64"); + f.addLocal("c", "i64"); + f.addLocal("m", "i64"); + + const c = f.getCodeBuilder(); + + const np32 = bigInt("100000000",16).minus( q.modInv(bigInt("100000000",16))).toJSNumber(); + + f.addCode(c.setLocal("np32", c.i64_const(np32))); + + for (let i=0; i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + [c0, c1] = [c1, c0]; + f.addCode( + c.setLocal(c1, + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquare() { + + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + f.addLocal("c0", "i64"); + f.addLocal("c1", "i64"); + f.addLocal("c0_old", "i64"); + f.addLocal("c1_old", "i64"); + f.addLocal("np32", "i64"); + + + for (let i=0;i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + + for (let i=Math.max(1, k-n32+1); (i<=k)&&(i=n32) { + f.addCode( + c.i64_store32( + c.getLocal("r"), + (k-n32)*4, + c.getLocal(c0) + ) + ); + } + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4-4, + c.getLocal(c0_old) + ) + ); + + f.addCode( + c.if( + c.i32_wrap_i64(c.getLocal(c1_old)), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + c.if( + c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ), + c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))), + ) + ) + ); + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r"))); + } + + function buildFromMontgomery() { + + const pAux2 = module.alloc(n8*2); + + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) )); + f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) )); + f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r"))); + } + + function buildInverse() { + + const f = module.addFunction(prefix+ "_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r"))); + f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))); + f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r"))); + } + + // Calculate various valuse needed for sqrt + + + let _nqr = bigInt(2); + if (q.isPrime()) { + while (!_nqr.modPow(_e, q).equals(_minusOne)) _nqr = _nqr.add(bigInt.one); + } + + const pnqr = module.alloc(utils.bigInt2BytesLE(_nqr.shiftLeft(n64*64).mod(q), n8)); + + let s2 = 0; + let _t = _minusOne; + + while ((!_t.isOdd())&&(!_t.isZero())) { + s2++; + _t = _t.shiftRight(1); + } + const pt = module.alloc(n8, utils.bigInt2BytesLE(_t, n8)); + + const _nqrToT = _nqr.modPow(_t, q); + const pNqrToT = module.alloc(utils.bigInt2BytesLE(_nqrToT.shiftLeft(n64*64).mod(q), n8)); + + const _tPlusOneOver2 = _t.add(1).shiftRight(1); + const ptPlusOneOver2 = module.alloc(n8, utils.bigInt2BytesLE(_tPlusOneOver2, n8)); + + function buildSqrt() { + + const f = module.addFunction(prefix+ "_sqrt"); + f.addParam("n", "i32"); + f.addParam("r", "i32"); + f.addLocal("m", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const C = c.i32_const(module.alloc(n8)); + const T = c.i32_const(module.alloc(n8)); + const R = c.i32_const(module.alloc(n8)); + const SQ = c.i32_const(module.alloc(n8)); + const B = c.i32_const(module.alloc(n8)); + + f.addCode( + + // If (n==0) return 0 + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret( + c.call(prefix + "_zero", c.getLocal("r")) + ) + ), + + c.setLocal("m", c.i32_const(s2)), + c.call(prefix + "_copy", c.i32_const(pNqrToT), C), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pt), c.i32_const(n8), T), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(ptPlusOneOver2), c.i32_const(n8), R), + + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", T, ONE)), + + c.call(prefix + "_square", T, SQ), + c.setLocal("i", c.i32_const(1)), + c.block(c.loop( + c.br_if(1, c.call(prefix + "_eq", SQ, ONE)), + c.call(prefix + "_square", SQ, SQ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_copy", C, B), + c.setLocal("j", c.i32_sub(c.i32_sub( c.getLocal("m"), c.getLocal("i")), c.i32_const(1)) ), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("j"))), + c.call(prefix + "_square", B, B), + c.setLocal("j", c.i32_sub(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("m", c.getLocal("i")), + c.call(prefix + "_square", B, C), + c.call(prefix + "_mul", T, C, T), + c.call(prefix + "_mul", R, B, R), + + c.br(0) + )), + + c.if( + c.call(prefix + "_isNegative", R), + c.call(prefix + "_neg", R, c.getLocal("r")), + c.call(prefix + "_copy", R, c.getLocal("r")), + ) + ); + } + + function buildIsSquare() { + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const ONE = c.i32_const(pOne); + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.if( + c.call(prefix + "_isZero", c.getLocal("n")), + c.ret(c.i32_const(1)) + ), + c.call(prefix + "_exp", c.getLocal("n"), c.i32_const(pe), c.i32_const(n8), AUX), + c.call(prefix + "_eq", AUX, ONE) + ); + } + + + function buildLoad() { + const f = module.addFunction(prefix+"_load"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + f.addLocal("p", "i32"); + f.addLocal("l", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + const c = f.getCodeBuilder(); + + const R = c.i32_const(module.alloc(n8)); + const pAux = module.alloc(n8); + const AUX = c.i32_const(pAux); + + f.addCode( + c.call(intPrefix + "_zero", c.getLocal("r")), + c.setLocal("i", c.i32_const(n8)), + c.setLocal("p", c.getLocal("scalar")), + c.block(c.loop( + c.br_if(1, c.i32_gt_u(c.getLocal("i"), c.getLocal("scalarLen"))), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", c.getLocal("p"), R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(n8))), + c.br(0) + )), + + c.setLocal("l", c.i32_rem_u( c.getLocal("scalarLen"), c.i32_const(n8))), + c.if(c.i32_eqz(c.getLocal("l")), c.ret([])), + c.call(intPrefix + "_zero", AUX), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if(1, c.i32_eq(c.getLocal("j"), c.getLocal("l"))), + + c.i32_store8( + c.getLocal("j"), + pAux, + c.i32_load8_u(c.getLocal("p")), + ), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(1))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.if( + c.i32_eq(c.getLocal("i"), c.i32_const(n8)), + c.call(prefix + "_one", R), + c.call(prefix + "_mul", R, c.i32_const(pR2), R) + ), + c.call(prefix + "_mul", AUX, R, AUX), + c.call(prefix + "_add", c.getLocal("r"), AUX, c.getLocal("r")), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const AUX = c.i32_const(module.alloc(n8)); + + f.addCode( + c.call(prefix + "_load", c.getLocal("scalar"), c.getLocal("scalarLen"), AUX), + c.call(prefix + "_toMontgomery", AUX, AUX), + c.call(prefix + "_mul", c.getLocal("x"), AUX, c.getLocal("r")), + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + f.addCode( + c.ret(c.call(intPrefix + "_eq", c.getLocal("x"), c.i32_const(pOne))) + ); + } + + + module.exportFunction(intPrefix + "_copy", prefix+"_copy"); + module.exportFunction(intPrefix + "_zero", prefix+"_zero"); + module.exportFunction(intPrefix + "_isZero", prefix+"_isZero"); + module.exportFunction(intPrefix + "_eq", prefix+"_eq"); + + buildIsOne(); + buildAdd(); + buildSub(); + buildNeg(); + buildMReduct(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildToMontgomery(); + buildFromMontgomery(); + buildIsNegative(); + buildSign(); + buildInverse(); + buildOne(); + buildLoad(); + buildTimesScalar(); + buildBatchInverse(module, prefix); + buildBatchConvertion(module, prefix + "_batchToMontgomery", prefix + "_toMontgomery", n8, n8); + buildBatchConvertion(module, prefix + "_batchFromMontgomery", prefix + "_fromMontgomery", n8, n8); + buildBatchConvertion(module, prefix + "_batchNeg", prefix + "_neg", n8, n8); + buildBatchOp(module, prefix + "_batchAdd", prefix + "_add", n8, n8); + buildBatchOp(module, prefix + "_batchSub", prefix + "_sub", n8, n8); + buildBatchOp(module, prefix + "_batchMul", prefix + "_mul", n8, n8); + + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_isNegative"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_mReduct"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_squareOld"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_inverse"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_load"); + module.exportFunction(prefix + "_timesScalar"); + buildExp( + module, + prefix + "_exp", + n8, + prefix + "_mul", + prefix + "_square", + intPrefix + "_copy", + prefix + "_one", + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_batchInverse"); + if (q.isPrime()) { + buildSqrt(); + buildIsSquare(); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + } + module.exportFunction(prefix + "_batchToMontgomery"); + module.exportFunction(prefix + "_batchFromMontgomery"); + // console.log(module.functionIdxByName); + + return prefix; +}; + + +/***/ }), + +/***/ 5420: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ +const buildExp = __webpack_require__(5107); +const buildBatchInverse = __webpack_require__(8163); +const bigInt = __webpack_require__(2096); +const utils = __webpack_require__(2333); + +module.exports = function buildF2m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + const q = module.modules[f1mPrefix].q; + + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*2 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + ); + } + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + function buildConjugate() { + const f = module.addFunction(prefix+"_conjugate"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + ); + } + + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ); + } + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const A = c.i32_const(module.alloc(f1n8)); + const B = c.i32_const(module.alloc(f1n8)); + const C = c.i32_const(module.alloc(f1n8)); + const D = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0 + c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1 + + c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1 + c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1 + c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1 + + // c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1) + c.call(mulNonResidueFn, B, r0), // r0 = nr*(x1*y1) + c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1) + c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1 + c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0 + ); + + } + + function buildMul1() { + const f = module.addFunction(prefix+"_mul1"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y = c.getLocal("y"); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + + f.addCode( + c.call(f1mPrefix + "_mul", x0, y, r0), // A = x0*y + c.call(f1mPrefix + "_mul", x1, y, r1), // B = x1*y + ); + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const AB = c.i32_const(module.alloc(f1n8)); + const APB = c.i32_const(module.alloc(f1n8)); + const APNB = c.i32_const(module.alloc(f1n8)); + const ABPNAB = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + // AB = x0*y1 + c.call(f1mPrefix + "_mul", x0, x1, AB), + + // APB = x0+y1 + c.call(f1mPrefix + "_add", x0, x1, APB), + + // APBN0 = x0 + nr*x1 + c.call(mulNonResidueFn, x1, APNB), + c.call(f1mPrefix + "_add", x0, APNB, APNB), + + // ABPNAB = ab + nr*ab + c.call(mulNonResidueFn, AB, ABPNAB), + c.call(f1mPrefix + "_add", ABPNAB, AB, ABPNAB), + + // r0 = APB * APNB - ABPNAB + c.call(f1mPrefix + "_mul", APB, APNB, r0), + c.call(f1mPrefix + "_sub", r0, ABPNAB, r0), + + // r1 = AB + AB + c.call(f1mPrefix + "_add", AB, AB, r1), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1) + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1) + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + // c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2), + c.call(mulNonResidueFn, t1, t2), + + c.call(f1mPrefix+"_sub", t0, t2, t2), + c.call(f1mPrefix+"_inverse", t2, t3), + + c.call(f1mPrefix+"_mul", x0, t3, r0), + c.call(f1mPrefix+"_mul", x1, t3, r1), + c.call(f1mPrefix+"_neg", r1, r1), + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + + f.addCode( + c.ret(c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1), + )) + ); + } + + + // Check here: https://eprint.iacr.org/2012/685.pdf + // Alg 9adj + function buildSqrt() { + + const f = module.addFunction(prefix+"_sqrt"); + f.addParam("a", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); + const e12 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(1)).divide(2), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + const n1a = c.i32_const(pn1); + const n1b = c.i32_const(pn1+f1n8); + const x0 = c.i32_const(module.alloc(f1n8*2)); + const b = c.i32_const(module.alloc(f1n8*2)); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if(c.call(prefix + "_eq",a0,n1), c.unreachable() ), + + // const x0 = F.mul(a1, a); + c.call(prefix + "_mul", a1, a, x0), + + // if (F.eq(alfa, F.negone)) { + c.if( + c.call(prefix + "_eq", alpha, n1), + [ + // x = F.mul(x0, [F.F.zero, F.F.one]); + ...c.call(f1mPrefix + "_zero", n1a), + ...c.call(f1mPrefix + "_one", n1b), + ...c.call(prefix + "_mul", n1, x0, c.getLocal("pr")), + ], + [ + // const b = F.pow(F.add(F.one, alfa), F.sqrt_e12); + ...c.call(prefix + "_one", b), + ...c.call(prefix + "_add", b, alpha, b), + ...c.call(prefix + "_exp", b, e12, c.i32_const(f1n8), b), + + // x = F.mul(b, x0); + ...c.call(prefix + "_mul", b, x0, c.getLocal("pr")), + ] + ) + ); + + } + + + function buildIsSquare() { + + const f = module.addFunction(prefix+"_isSquare"); + f.addParam("a", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const e34 = c.i32_const(module.alloc(utils.bigInt2BytesLE(bigInt(q).minus(bigInt(3)).divide(4), f1n8 ))); + + const a = c.getLocal("a"); + const a1 = c.i32_const(module.alloc(f1n8*2)); + const alpha = c.i32_const(module.alloc(f1n8*2)); + const a0 = c.i32_const(module.alloc(f1n8*2)); + const pn1 = module.alloc(f1n8*2); + const n1 = c.i32_const(pn1); + + f.addCode( + + c.call(prefix + "_one", n1), + c.call(prefix + "_neg", n1, n1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_exp", a, e34, c.i32_const(f1n8), a1), + + // const a1 = F.pow(a, F.sqrt_e34); + c.call(prefix + "_square", a1, alpha), + c.call(prefix + "_mul", a, alpha, alpha), + + // const a0 = F.mul(F.frobenius(1, alfa), alfa); + c.call(prefix + "_conjugate", alpha, a0), + c.call(prefix + "_mul", a0, alpha, a0), + + // if (F.eq(a0, F.negone)) return null; + c.if( + c.call( + prefix + "_eq", + a0, + n1 + ), + c.ret(c.i32_const(0)) + ), + c.ret(c.i32_const(1)) + ); + + } + + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildMul1(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildConjugate(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildSign(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_mul1"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_conjugate"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*2, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one", + ); + buildSqrt(); + buildIsSquare(); + + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_sqrt"); + module.exportFunction(prefix + "_isSquare"); + module.exportFunction(prefix + "_isNegative"); + + + return prefix; +}; + + +/***/ }), + +/***/ 7173: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ +const buildExp = __webpack_require__(5107); +const buildBatchInverse = __webpack_require__(8163); + +module.exports = function buildF3m(module, mulNonResidueFn, prefix, f1mPrefix) { + + if (module.modules[prefix]) return prefix; // already builded + + const f1n8 = module.modules[f1mPrefix].n64*8; + module.modules[prefix] = { + n64: module.modules[f1mPrefix].n64*3 + }; + + function buildAdd() { + const f = module.addFunction(prefix+"_add"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_add", x0, y0, r0), + c.call(f1mPrefix+"_add", x1, y1, r1), + c.call(f1mPrefix+"_add", x2, y2, r2), + ); + } + + function buildTimesScalar() { + const f = module.addFunction(prefix+"_timesScalar"); + f.addParam("x", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLen", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_timesScalar", x0, c.getLocal("scalar"), c.getLocal("scalarLen"), r0), + c.call(f1mPrefix+"_timesScalar", x1, c.getLocal("scalar"), c.getLocal("scalarLen"), r1), + c.call(f1mPrefix+"_timesScalar", x2, c.getLocal("scalar"), c.getLocal("scalarLen"), r2), + ); + } + + + function buildSub() { + const f = module.addFunction(prefix+"_sub"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_sub", x0, y0, r0), + c.call(f1mPrefix+"_sub", x1, y1, r1), + c.call(f1mPrefix+"_sub", x2, y2, r2), + ); + } + + function buildNeg() { + const f = module.addFunction(prefix+"_neg"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_neg", x0, r0), + c.call(f1mPrefix+"_neg", x1, r1), + c.call(f1mPrefix+"_neg", x2, r2), + ); + } + + function buildIsNegative() { + const f = module.addFunction(prefix+"_isNegative"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.if( + c.call(f1mPrefix+"_isZero", x2), + c.if( + c.call(f1mPrefix+"_isZero", x1), + c.ret(c.call(f1mPrefix+"_isNegative", x0)), + c.ret(c.call(f1mPrefix+"_isNegative", x1)) + ) + ), + c.ret(c.call(f1mPrefix+"_isNegative", x2)) + ); + } + + + function buildMul() { + const f = module.addFunction(prefix+"_mul"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.addParam("r", "i32"); + + const cd = f.getCodeBuilder(); + + const a = cd.getLocal("x"); + const b = cd.i32_add(cd.getLocal("x"), cd.i32_const(f1n8)); + const c = cd.i32_add(cd.getLocal("x"), cd.i32_const(2*f1n8)); + const A = cd.getLocal("y"); + const B = cd.i32_add(cd.getLocal("y"), cd.i32_const(f1n8)); + const C = cd.i32_add(cd.getLocal("y"), cd.i32_const(2*f1n8)); + const r0 = cd.getLocal("r"); + const r1 = cd.i32_add(cd.getLocal("r"), cd.i32_const(f1n8)); + const r2 = cd.i32_add(cd.getLocal("r"), cd.i32_const(2*f1n8)); + + const aA = cd.i32_const(module.alloc(f1n8)); + const bB = cd.i32_const(module.alloc(f1n8)); + const cC = cd.i32_const(module.alloc(f1n8)); + const a_b = cd.i32_const(module.alloc(f1n8)); + const A_B = cd.i32_const(module.alloc(f1n8)); + const a_c = cd.i32_const(module.alloc(f1n8)); + const A_C = cd.i32_const(module.alloc(f1n8)); + const b_c = cd.i32_const(module.alloc(f1n8)); + const B_C = cd.i32_const(module.alloc(f1n8)); + const aA_bB = cd.i32_const(module.alloc(f1n8)); + const aA_cC = cd.i32_const(module.alloc(f1n8)); + const bB_cC = cd.i32_const(module.alloc(f1n8)); + const AUX = cd.i32_const(module.alloc(f1n8)); + + + f.addCode( + cd.call(f1mPrefix + "_mul", a, A, aA), + cd.call(f1mPrefix + "_mul", b, B, bB), + cd.call(f1mPrefix + "_mul", c, C, cC), + + cd.call(f1mPrefix + "_add", a, b, a_b), + cd.call(f1mPrefix + "_add", A, B, A_B), + cd.call(f1mPrefix + "_add", a, c, a_c), + cd.call(f1mPrefix + "_add", A, C, A_C), + cd.call(f1mPrefix + "_add", b, c, b_c), + cd.call(f1mPrefix + "_add", B, C, B_C), + + cd.call(f1mPrefix + "_add", aA, bB, aA_bB), + cd.call(f1mPrefix + "_add", aA, cC, aA_cC), + cd.call(f1mPrefix + "_add", bB, cC, bB_cC), + + cd.call(f1mPrefix + "_mul", b_c, B_C, r0), + cd.call(f1mPrefix + "_sub", r0, bB_cC, r0), + cd.call(mulNonResidueFn, r0, r0), + cd.call(f1mPrefix + "_add", aA, r0, r0), + + cd.call(f1mPrefix + "_mul", a_b, A_B, r1), + cd.call(f1mPrefix + "_sub", r1, aA_bB, r1), + cd.call(mulNonResidueFn, cC, AUX), + cd.call(f1mPrefix + "_add", r1, AUX, r1), + + cd.call(f1mPrefix + "_mul", a_c, A_C, r2), + cd.call(f1mPrefix + "_sub", r2, aA_cC, r2), + cd.call(f1mPrefix + "_add", r2, bB, r2), + ); + + } + + function buildSquare() { + const f = module.addFunction(prefix+"_square"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const A = c.getLocal("x"); + const B = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const C = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const s0 = c.i32_const(module.alloc(f1n8)); + const ab = c.i32_const(module.alloc(f1n8)); + const s1 = c.i32_const(module.alloc(f1n8)); + const s2 = c.i32_const(module.alloc(f1n8)); + const bc = c.i32_const(module.alloc(f1n8)); + const s3 = c.i32_const(module.alloc(f1n8)); + const s4 = c.i32_const(module.alloc(f1n8)); + + + f.addCode( + + c.call(f1mPrefix + "_square", A, s0), + c.call(f1mPrefix + "_mul", A, B, ab), + c.call(f1mPrefix + "_add", ab, ab, s1), + + c.call(f1mPrefix + "_sub", A, B, s2), + c.call(f1mPrefix + "_add", s2, C, s2), + c.call(f1mPrefix + "_square", s2, s2), + + c.call(f1mPrefix + "_mul", B, C, bc), + c.call(f1mPrefix + "_add", bc, bc, s3), + + c.call(f1mPrefix + "_square", C, s4), + + c.call(mulNonResidueFn, s3, r0), + c.call(f1mPrefix + "_add", s0, r0, r0), + + c.call(mulNonResidueFn, s4, r1), + c.call(f1mPrefix + "_add", s1, r1, r1), + + c.call(f1mPrefix + "_add", s0, s4, r2), + c.call(f1mPrefix + "_sub", s3, r2, r2), + c.call(f1mPrefix + "_add", s2, r2, r2), + c.call(f1mPrefix + "_add", s1, r2, r2), + ); + + } + + + function buildToMontgomery() { + const f = module.addFunction(prefix+"_toMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_toMontgomery", x0, r0), + c.call(f1mPrefix+"_toMontgomery", x1, r1), + c.call(f1mPrefix+"_toMontgomery", x2, r2) + ); + } + + function buildFromMontgomery() { + const f = module.addFunction(prefix+"_fromMontgomery"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_fromMontgomery", x0, r0), + c.call(f1mPrefix+"_fromMontgomery", x1, r1), + c.call(f1mPrefix+"_fromMontgomery", x2, r2) + ); + } + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_copy", x0, r0), + c.call(f1mPrefix+"_copy", x1, r1), + c.call(f1mPrefix+"_copy", x2, r2), + ); + } + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_zero", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildOne() { + const f = module.addFunction(prefix+"_one"); + f.addParam("x", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.call(f1mPrefix+"_one", x0), + c.call(f1mPrefix+"_zero", x1), + c.call(f1mPrefix+"_zero", x2), + ); + } + + function buildEq() { + const f = module.addFunction(prefix+"_eq"); + f.addParam("x", "i32"); + f.addParam("y", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const y0 = c.getLocal("y"); + const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8)); + const y2 = c.i32_add(c.getLocal("y"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_eq", x0, y0), + c.call(f1mPrefix+"_eq", x1, y1), + ), + c.call(f1mPrefix+"_eq", x2, y2) + ) + ); + } + + function buildIsZero() { + const f = module.addFunction(prefix+"_isZero"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.i32_and( + c.i32_and( + c.call(f1mPrefix+"_isZero", x0), + c.call(f1mPrefix+"_isZero", x1) + ), + c.call(f1mPrefix+"_isZero", x2) + ) + ); + } + + function buildInverse() { + const f = module.addFunction(prefix+"_inverse"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + const r0 = c.getLocal("r"); + const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8)); + const r2 = c.i32_add(c.getLocal("r"), c.i32_const(2*f1n8)); + + const t0 = c.i32_const(module.alloc(f1n8)); + const t1 = c.i32_const(module.alloc(f1n8)); + const t2 = c.i32_const(module.alloc(f1n8)); + const t3 = c.i32_const(module.alloc(f1n8)); + const t4 = c.i32_const(module.alloc(f1n8)); + const t5 = c.i32_const(module.alloc(f1n8)); + const c0 = c.i32_const(module.alloc(f1n8)); + const c1 = c.i32_const(module.alloc(f1n8)); + const c2 = c.i32_const(module.alloc(f1n8)); + const t6 = c.i32_const(module.alloc(f1n8)); + const AUX = c.i32_const(module.alloc(f1n8)); + + f.addCode( + c.call(f1mPrefix+"_square", x0, t0), + c.call(f1mPrefix+"_square", x1, t1), + c.call(f1mPrefix+"_square", x2, t2), + c.call(f1mPrefix+"_mul", x0, x1, t3), + c.call(f1mPrefix+"_mul", x0, x2, t4), + c.call(f1mPrefix+"_mul", x1, x2, t5), + + c.call(mulNonResidueFn, t5, c0), + c.call(f1mPrefix+"_sub", t0, c0, c0), + + c.call(mulNonResidueFn, t2, c1), + c.call(f1mPrefix+"_sub", c1, t3, c1), + + c.call(f1mPrefix+"_sub", t1, t4, c2), + + c.call(f1mPrefix+"_mul", x2, c1, t6), + c.call(f1mPrefix+"_mul", x1, c2, AUX), + c.call(f1mPrefix+"_add", t6, AUX, t6), + c.call(mulNonResidueFn, t6, t6), + c.call(f1mPrefix+"_mul", x0, c0, AUX), + c.call(f1mPrefix+"_add", AUX, t6, t6), + + c.call(f1mPrefix+"_inverse", t6, t6), + + c.call(f1mPrefix+"_mul", t6, c0, r0), + c.call(f1mPrefix+"_mul", t6, c1, r1), + c.call(f1mPrefix+"_mul", t6, c2, r2) + ); + } + + + function buildSign() { + const f = module.addFunction(prefix+"_sign"); + f.addParam("x", "i32"); + f.addLocal("s", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(2*f1n8)); + + f.addCode( + c.setLocal("s" , c.call( f1mPrefix + "_sign", x2)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.setLocal("s" , c.call( f1mPrefix + "_sign", x1)), + c.if( + c.getLocal("s"), + c.ret(c.getLocal("s")) + ), + c.ret(c.call( f1mPrefix + "_sign", x0)) + ); + } + + function buildIsOne() { + const f = module.addFunction(prefix+"_isOne"); + f.addParam("x", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + const x0 = c.getLocal("x"); + const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8)); + const x2 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8*2)); + + f.addCode( + c.ret( + c.i32_and( + c.i32_and( + c.call(f1mPrefix + "_isOne", x0), + c.call(f1mPrefix + "_isZero", x1) + ), + c.call(f1mPrefix + "_isZero", x2) + ) + ) + ); + } + + buildIsZero(); + buildIsOne(); + buildZero(); + buildOne(); + buildCopy(); + buildMul(); + buildSquare(); + buildAdd(); + buildSub(); + buildNeg(); + buildSign(); + buildToMontgomery(); + buildFromMontgomery(); + buildEq(); + buildInverse(); + buildTimesScalar(); + buildIsNegative(); + + module.exportFunction(prefix + "_isZero"); + module.exportFunction(prefix + "_isOne"); + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_one"); + module.exportFunction(prefix + "_copy"); + module.exportFunction(prefix + "_mul"); + module.exportFunction(prefix + "_square"); + module.exportFunction(prefix + "_add"); + module.exportFunction(prefix + "_sub"); + module.exportFunction(prefix + "_neg"); + module.exportFunction(prefix + "_sign"); + module.exportFunction(prefix + "_fromMontgomery"); + module.exportFunction(prefix + "_toMontgomery"); + module.exportFunction(prefix + "_eq"); + module.exportFunction(prefix + "_inverse"); + buildBatchInverse(module, prefix); + buildExp( + module, + prefix + "_exp", + f1n8*3, + prefix + "_mul", + prefix + "_square", + prefix + "_copy", + prefix + "_one" + ); + module.exportFunction(prefix + "_exp"); + module.exportFunction(prefix + "_timesScalar"); + module.exportFunction(prefix + "_batchInverse"); + module.exportFunction(prefix + "_isNegative"); + + return prefix; +}; + + +/***/ }), + +/***/ 3911: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(2096); +const utils = __webpack_require__(2333); + +module.exports = function buildFFT(module, prefix, gPrefix, fPrefix, opGtimesF) { + + const n64f = module.modules[fPrefix].n64; + const n8f = n64f*8; + + const n64g = module.modules[gPrefix].n64; + const n8g = n64g*8; + + const q = module.modules[fPrefix].q; + + let rem = q.minus(bigInt(1)); + let maxBits = 0; + while (!rem.isOdd()) { + maxBits ++; + rem = rem.shiftRight(1); + } + + let nr = bigInt(2); + + while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1); + + // console.log(nr); + + const w = new Array(maxBits+1); + w[maxBits] = nr.modPow(rem, q); + + let n=maxBits-1; + while (n>=0) { + w[n] = w[n+1].modPow(2, q); + n--; + } + + const bytes = []; + const R = bigInt(1).shiftLeft(n8f*8).mod(q); + + for (let i=0; i> i); + } + } + return r; + } + + const rtable = Array(256); + for (let i=0; i<256; i++) { + rtable[i] = rev(i); + } + + const REVTABLE = module.alloc(rtable); + + + function buildLog2() { + const f = module.addFunction(prefix+"__log2"); + f.addParam("n", "i32"); + f.setReturnType("i32"); + f.addLocal("bits", "i32"); + f.addLocal("aux", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ) + ); + f.addCode(c.setLocal("bits", c.i32_const(0))); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_eqz(c.getLocal("aux")) + ), + + c.setLocal( + "aux", + c.i32_shr_u( + c.getLocal("aux"), + c.i32_const(1) + ) + ), + + c.setLocal( + "bits", + c.i32_add( + c.getLocal("bits"), + c.i32_const(1) + ) + ), + + c.br(0) + ))); + + f.addCode(c.if( + c.i32_ne( + c.getLocal("n"), + c.i32_shl( + c.i32_const(1), + c.getLocal("bits") + ) + ), + c.unreachable() + )); + + f.addCode(c.if( + c.i32_gt_u( + c.getLocal("bits"), + c.i32_const(maxBits) + ), + c.unreachable() + )); + + f.addCode(c.getLocal("bits")); + } + + function buildFFT() { + const f = module.addFunction(prefix+"_fft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + + f.addLocal("bits", "i32"); + + const c = f.getCodeBuilder(); + + const One = c.i32_const(module.alloc(n8f)); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.call(fPrefix + "_one", One), + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(0), + One + ) + ); + + } + + function buildIFFT() { + const f = module.addFunction(prefix+"_ifft"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("bits", "i32"); + f.addLocal("pInv2", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal( + "bits", + c.call( + prefix + "__log2", + c.getLocal("n") + ) + ), + c.setLocal( + "pInv2", + c.i32_add( + c.i32_const(INV2), + c.i32_mul( + c.getLocal("bits"), + c.i32_const(n8f) + ) + ) + ), + + c.call( + prefix+"_rawfft", + c.getLocal("px"), + c.getLocal("bits"), + c.i32_const(1), + c.getLocal("pInv2") + ), + ); + } + + function buildRawFFT() { + const f = module.addFunction(prefix+"_rawfft"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); // 2 power + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + + f.addLocal("s", "i32"); + f.addLocal("k", "i32"); + f.addLocal("j", "i32"); + f.addLocal("m", "i32"); + f.addLocal("mdiv2", "i32"); + f.addLocal("n", "i32"); + f.addLocal("pwm", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call(prefix + "__reversePermutation", c.getLocal("px"), c.getLocal("bits")), + c.setLocal("n", c.i32_shl(c.i32_const(1), c.getLocal("bits"))), + c.setLocal("s", c.i32_const(1)), + c.block(c.loop( + c.br_if( + 1, + c.i32_gt_u( + c.getLocal("s"), + c.getLocal("bits") + ) + ), + c.setLocal("m", c.i32_shl(c.i32_const(1), c.getLocal("s"))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("s"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("k", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("k"), + c.getLocal("n") + ) + ), + + c.call(fPrefix + "_one", W), + + c.setLocal("mdiv2", c.i32_shr_u(c.getLocal("m"), c.i32_const(1)) ), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("j"), + c.getLocal("mdiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_add( + c.getLocal("k"), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.i32_mul( + c.getLocal("mdiv2"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("k", c.i32_add(c.getLocal("k"), c.getLocal("m"))), + c.br(0) + )), + + c.setLocal("s", c.i32_add(c.getLocal("s"), c.i32_const(1))), + c.br(0) + )), + c.call( + prefix + "__fftFinal", + c.getLocal("px"), + c.getLocal("bits"), + c.getLocal("reverse"), + c.getLocal("mulFactor") + ) + ); + } + + + function buildFinalInverse() { + const f = module.addFunction(prefix+"__fftFinal"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addParam("reverse", "i32"); + f.addParam("mulFactor", "i32"); + f.addLocal("n", "i32"); + f.addLocal("ndiv2", "i32"); + f.addLocal("pInv2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("mask", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.if( + c.i32_and( + c.i32_eqz(c.getLocal("reverse")), + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")) + ), + c.ret([]) + ), + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + + c.setLocal("mask", c.i32_sub( c.getLocal("n") , c.i32_const(1))), + c.setLocal("i", c.i32_const(1)), + c.setLocal( + "ndiv2", + c.i32_shr_u( + c.getLocal("n"), + c.i32_const(1) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.i32_sub( + c.getLocal("n"), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.getLocal("reverse"), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1") ), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")), + ], + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , T , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ), + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF , c.getLocal("idx1") , c.getLocal("mulFactor"), c.getLocal("idx1") ), + ...c.call(opGtimesF , c.getLocal("idx2") , c.getLocal("mulFactor"), c.getLocal("idx2")), + ] + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )), + + c.if( + c.call(fPrefix + "_isOne", c.getLocal("mulFactor")), + [ + // Do nothing (It should not be here) + ], + [ + ...c.call(opGtimesF, c.getLocal("px") , c.getLocal("mulFactor"), c.getLocal("px")), + ...c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ) + ), + ...c.call(opGtimesF, c.getLocal("idx2"),c.getLocal("mulFactor"), c.getLocal("idx2")) + ] + ) + ); + } + + function buildReversePermutation() { + const f = module.addFunction(prefix+"__reversePermutation"); + f.addParam("px", "i32"); + f.addParam("bits", "i32"); + f.addLocal("n", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ri", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal("idx1", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("ri", c.call(prefix + "__rev", c.getLocal("i"), c.getLocal("bits"))), + + c.setLocal("idx2", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("ri"), + c.i32_const(n8g) + ) + ) + ), + + c.if( + c.i32_lt_u( + c.getLocal("i"), + c.getLocal("ri") + ), + [ + ...c.call(gPrefix + "_copy", c.getLocal("idx1"), T), + ...c.call(gPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1")), + ...c.call(gPrefix + "_copy", T , c.getLocal("idx2")) + ] + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + + c.br(0) + )) + ); + } + + function buildRev() { + const f = module.addFunction(prefix+"__rev"); + f.addParam("x", "i32"); + f.addParam("bits", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.i32_rotl( + c.i32_add( + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.getLocal("x"), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(24) + ), + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(8) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(16) + ), + ), + c.i32_add( + c.i32_shl( + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(16) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + c.i32_const(8) + ), + c.i32_load8_u( + c.i32_and( + c.i32_shr_u( + c.getLocal("x"), + c.i32_const(24) + ), + c.i32_const(0xFF) + ), + REVTABLE, + 0 + ), + ) + ), + c.getLocal("bits") + ) + ); + } + + + function buildFFTJoin() { + const f = module.addFunction(prefix+"_fftJoin"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W, + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + function buildFFTJoinExt() { + const f = module.addFunction(prefix+"_fftJoinExt"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + U + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pShiftToM"), + c.getLocal("idx2") + ), + + c.call( + gPrefix + "_add", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + U, + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTJoinExtInv() { + const f = module.addFunction(prefix+"_fftJoinExtInv"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + U, + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("pSConst"), + c.getLocal("idx2") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + c.getLocal("idx1") + ), + + c.call( + gPrefix + "_sub", + U, + c.getLocal("idx1"), + c.getLocal("idx1") + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pSConst"), + c.getLocal("idx1") + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + + function buildPrepareLagrangeEvaluation() { + const f = module.addFunction(prefix+"_prepareLagrangeEvaluation"); + f.addParam("pBuff1", "i32"); + f.addParam("pBuff2", "i32"); + f.addParam("n", "i32"); + f.addParam("first", "i32"); + f.addParam("inc", "i32"); + f.addParam("totalBits", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("pShiftToM", "i32"); + f.addLocal("pSConst", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + + c.setLocal("pShiftToM", + c.i32_add( + c.i32_const(SHIFT_TO_M), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("pSConst", + c.i32_add( + c.i32_const(SCONST), + c.i32_mul( + c.getLocal("totalBits"), + c.i32_const(n8f) + ) + ) + ), + + + c.call( fPrefix + "_copy", c.getLocal("first"), W), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("n") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff1"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff2"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("pShiftToM"), + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx2"), + U, + U + ), + + c.call( + gPrefix + "_sub", + c.getLocal("idx1"), + c.getLocal("idx2"), + c.getLocal("idx2"), + ), + + c.call( + opGtimesF, + U, + c.getLocal("pSConst"), + c.getLocal("idx1"), + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("inc"), + W + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + function buildFFTMix() { + const f = module.addFunction(prefix+"_fftMix"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("exp", "i32"); + f.addLocal("nGroups", "i32"); + f.addLocal("nPerGroup", "i32"); + f.addLocal("nPerGroupDiv2", "i32"); + f.addLocal("pairOffset", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pwm", "i32"); + + const c = f.getCodeBuilder(); + + const W = c.i32_const(module.alloc(n8f)); + const T = c.i32_const(module.alloc(n8g)); + const U = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("nPerGroup", c.i32_shl(c.i32_const(1), c.getLocal("exp"))), + c.setLocal("nPerGroupDiv2", c.i32_shr_u(c.getLocal("nPerGroup"), c.i32_const(1))), + c.setLocal("nGroups", c.i32_shr_u(c.getLocal("n"), c.getLocal("exp"))), + c.setLocal("pairOffset", c.i32_mul(c.getLocal("nPerGroupDiv2"), c.i32_const(n8g))), + c.setLocal("pwm", + c.i32_add( + c.i32_const(ROOTs), + c.i32_mul( + c.getLocal("exp"), + c.i32_const(n8f) + ) + ) + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nGroups") + ) + ), + c.call( fPrefix + "_one", W), + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nPerGroupDiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_add( + c.i32_mul( + c.getLocal("i"), + c.getLocal("nPerGroup") + ), + c.getLocal("j") + ), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("idx1"), + c.getLocal("pairOffset") + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + W, + T + ), + + c.call( + gPrefix + "_copy", + c.getLocal("idx1"), + U + ), + + c.call( + gPrefix + "_add", + U, + T, + c.getLocal("idx1"), + ), + + c.call( + gPrefix + "_sub", + U, + T, + c.getLocal("idx2"), + ), + + c.call( + fPrefix + "_mul", + W, + c.getLocal("pwm"), + W, + ), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + + // Reverse all and multiply by factor + function buildFFTFinal() { + const f = module.addFunction(prefix+"_fftFinal"); + f.addParam("pBuff", "i32"); + f.addParam("n", "i32"); + f.addParam("factor", "i32"); + f.addLocal("idx1", "i32"); + f.addLocal("idx2", "i32"); + f.addLocal("i", "i32"); + f.addLocal("ndiv2", "i32"); + + const c = f.getCodeBuilder(); + + const T = c.i32_const(module.alloc(n8g)); + + f.addCode( + c.setLocal("ndiv2", c.i32_shr_u(c.getLocal("n"), c.i32_const(1))), + c.if( + c.i32_and( + c.getLocal("n"), + c.i32_const(1) + ), + c.call( + opGtimesF, + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + c.getLocal("factor"), + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("ndiv2"), + c.i32_const(n8g) + ) + ), + ), + ), + c.setLocal("i", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_ge_u( + c.getLocal("i"), + c.getLocal("ndiv2") + ) + ), + + c.setLocal( + "idx1", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.getLocal("i"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal( + "idx2", + c.i32_add( + c.getLocal("pBuff"), + c.i32_mul( + c.i32_sub( + c.i32_sub( + c.getLocal("n"), + c.i32_const(1) + ), + c.getLocal("i") + ), + c.i32_const(n8g) + ) + ) + ), + + c.call( + opGtimesF, + c.getLocal("idx2"), + c.getLocal("factor"), + T + ), + + c.call( + opGtimesF, + c.getLocal("idx1"), + c.getLocal("factor"), + c.getLocal("idx2"), + ), + + c.call( + gPrefix + "_copy", + T, + c.getLocal("idx1"), + ), + + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + } + + buildRev(); + buildReversePermutation(); + buildFinalInverse(); + buildRawFFT(); + buildLog2(); + buildFFT(); + buildIFFT(); + buildFFTJoin(); + buildFFTJoinExt(); + buildFFTJoinExtInv(); + buildFFTMix(); + buildFFTFinal(); + buildPrepareLagrangeEvaluation(); + + module.exportFunction(prefix+"_fft"); + module.exportFunction(prefix+"_ifft"); + module.exportFunction(prefix+"_rawfft"); + module.exportFunction(prefix+"_fftJoin"); + module.exportFunction(prefix+"_fftJoinExt"); + module.exportFunction(prefix+"_fftJoinExtInv"); + module.exportFunction(prefix+"_fftMix"); + module.exportFunction(prefix+"_fftFinal"); + module.exportFunction(prefix+"_prepareLagrangeEvaluation"); + +}; + + +/***/ }), + +/***/ 6754: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const utils = __webpack_require__(2333); + +module.exports = function buildInt(module, n64, _prefix) { + + const prefix = _prefix || "int"; + if (module.modules[prefix]) return prefix; // already builded + module.modules[prefix] = {}; + + const n32 = n64*2; + const n8 = n64*8; + + const one = module.alloc(n8, utils.bigInt2BytesLE(1, n8)); + + function buildCopy() { + const f = module.addFunction(prefix+"_copy"); + f.addParam("px", "i32"); + f.addParam("pr", "i32"); + + const c = f.getCodeBuilder(); + + for (let i=0; i>1) )&&(i>1, k>>1) + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ) + ) + ); + } + + // Add the old carry + + if (k>0) { + f.addCode( + c.setLocal(c0, + c.i64_add( + c.i64_and( + c.getLocal(c0), + c.i64_const(0xFFFFFFFF) + ), + c.i64_and( + c.getLocal(c0_old), + c.i64_const(0xFFFFFFFF) + ), + ) + ) + ); + + f.addCode( + c.setLocal(c1, + c.i64_add( + c.i64_add( + c.getLocal(c1), + c.i64_shr_u( + c.getLocal(c0), + c.i64_const(32) + ) + ), + c.getLocal(c1_old) + ) + ) + ); + } + + f.addCode( + c.i64_store32( + c.getLocal("r"), + k*4, + c.getLocal(c0) + ) + ); + + f.addCode( + c.setLocal( + c0_old, + c.getLocal(c1) + ), + c.setLocal( + c1_old, + c.i64_shr_u( + c.getLocal(c0_old), + c.i64_const(32) + ) + ) + ); + + } + f.addCode( + c.i64_store32( + c.getLocal("r"), + n32*4*2-4, + c.getLocal(c0_old) + ) + ); + + } + + + function buildSquareOld() { + const f = module.addFunction(prefix+"_squareOld"); + f.addParam("x", "i32"); + f.addParam("r", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode(c.call(prefix + "_mul", c.getLocal("x"), c.getLocal("x"), c.getLocal("r"))); + } + + function _buildMul1() { + const f = module.addFunction(prefix+"__mul1"); + f.addParam("px", "i32"); + f.addParam("y", "i64"); + f.addParam("pr", "i32"); + f.addLocal("c", "i64"); + + const c = f.getCodeBuilder(); + + f.addCode(c.setLocal( + "c", + c.i64_mul( + c.i64_load32_u(c.getLocal("px"), 0, 0), + c.getLocal("y") + ) + )); + + f.addCode(c.i64_store32( + c.getLocal("pr"), + 0, + 0, + c.getLocal("c"), + )); + + for (let i=1; i3)&&(Y[eY]==0) ey--; + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(Y , c.getLocal("eY")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eY"), + c.i32_const(3) + ) + ) + ), + c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))), + c.br(0) + ))); + + f.addCode( + c.setLocal( + "sy", + c.i64_add( + c.i64_load32_u( + c.i32_sub( + c.i32_add( Y, c.getLocal("eY")), + c.i32_const(3) + ), + 0, + 0 + ), + c.i64_const(1) + ) + ) + ); + + // Force a divide by 0 if quotien is 0 + f.addCode( + c.if( + c.i64_eq( + c.getLocal("sy"), + c.i64_const(1) + ), + c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0))) + ) + ); + + f.addCode(c.block(c.loop( + + // while (eX>7)&&(Y[eX]==0) ex--; + c.block(c.loop( + c.br_if( + 1, + c.i32_or( + c.i32_load8_u( + c.i32_add(R , c.getLocal("eX")), + 0, + 0 + ), + c.i32_eq( + c.getLocal("eX"), + c.i32_const(7) + ) + ) + ), + c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal( + "sx", + c.i64_load( + c.i32_sub( + c.i32_add( R, c.getLocal("eX")), + c.i32_const(7) + ), + 0, + 0 + ) + ), + + c.setLocal( + "sx", + c.i64_div_u( + c.getLocal("sx"), + c.getLocal("sy") + ) + ), + c.setLocal( + "ec", + c.i32_sub( + c.i32_sub( + c.getLocal("eX"), + c.getLocal("eY") + ), + c.i32_const(4) + ) + ), + + // While greater than 32 bits or ec is neg, shr and inc exp + c.block(c.loop( + c.br_if( + 1, + c.i32_and( + c.i64_eqz( + c.i64_and( + c.getLocal("sx"), + c.i64_const("0xFFFFFFFF00000000") + ) + ), + c.i32_ge_s( + c.getLocal("ec"), + c.i32_const(0) + ) + ) + ), + + c.setLocal( + "sx", + c.i64_shr_u( + c.getLocal("sx"), + c.i64_const(8) + ) + ), + + c.setLocal( + "ec", + c.i32_add( + c.getLocal("ec"), + c.i32_const(1) + ) + ), + c.br(0) + )), + + c.if( + c.i64_eqz(c.getLocal("sx")), + [ + ...c.br_if( + 2, + c.i32_eqz(c.call(prefix + "_gte", R, Y)) + ), + ...c.setLocal("sx", c.i64_const(1)), + ...c.setLocal("ec", c.i32_const(0)) + ] + ), + + c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2), + c.drop(c.call( + prefix + "_sub", + R, + c.i32_sub(R2, c.getLocal("ec")), + R + )), + c.call( + prefix + "__add1", + c.i32_add(C, c.getLocal("ec")), + c.getLocal("sx") + ), + c.br(0) + ))); + } + + function buildInverseMod() { + + const f = module.addFunction(prefix+"_inverseMod"); + f.addParam("px", "i32"); + f.addParam("pm", "i32"); + f.addParam("pr", "i32"); + f.addLocal("t", "i32"); + f.addLocal("newt", "i32"); + f.addLocal("r", "i32"); + f.addLocal("qq", "i32"); + f.addLocal("qr", "i32"); + f.addLocal("newr", "i32"); + f.addLocal("swp", "i32"); + f.addLocal("x", "i32"); + f.addLocal("signt", "i32"); + f.addLocal("signnewt", "i32"); + f.addLocal("signx", "i32"); + + const c = f.getCodeBuilder(); + + const aux1 = c.i32_const(module.alloc(n8)); + const aux2 = c.i32_const(module.alloc(n8)); + const aux3 = c.i32_const(module.alloc(n8)); + const aux4 = c.i32_const(module.alloc(n8)); + const aux5 = c.i32_const(module.alloc(n8)); + const aux6 = c.i32_const(module.alloc(n8)); + const mulBuff = c.i32_const(module.alloc(n8*2)); + const aux7 = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("t", aux1), + c.call(prefix + "_zero", aux1), + c.setLocal("signt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("r", aux2), + c.call(prefix + "_copy", c.getLocal("pm"), aux2) + ); + + f.addCode( + c.setLocal("newt", aux3), + c.call(prefix + "_one", aux3), + c.setLocal("signnewt", c.i32_const(0)), + ); + + f.addCode( + c.setLocal("newr", aux4), + c.call(prefix + "_copy", c.getLocal("px"), aux4) + ); + + + + + f.addCode(c.setLocal("qq", aux5)); + f.addCode(c.setLocal("qr", aux6)); + f.addCode(c.setLocal("x", aux7)); + + f.addCode(c.block(c.loop( + c.br_if( + 1, + c.call(prefix + "_isZero", c.getLocal("newr") ) + ), + c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")), + + c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff), + + c.if( + c.getLocal("signt"), + c.if( + c.getLocal("signnewt"), + c.if ( + c.call(prefix + "_gte", mulBuff, c.getLocal("t")), + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ], + ), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ), + c.if( + c.getLocal("signnewt"), + [ + ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + c.if ( + c.call(prefix + "_gte", c.getLocal("t"), mulBuff), + [ + ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(0)) + ], + [ + ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))), + ...c.setLocal("signx", c.i32_const(1)) + ] + ) + ) + ), + + c.setLocal("swp", c.getLocal("t")), + c.setLocal("t", c.getLocal("newt")), + c.setLocal("newt", c.getLocal("x")), + c.setLocal("x", c.getLocal("swp")), + + c.setLocal("signt", c.getLocal("signnewt")), + c.setLocal("signnewt", c.getLocal("signx")), + + c.setLocal("swp", c.getLocal("r")), + c.setLocal("r", c.getLocal("newr")), + c.setLocal("newr", c.getLocal("qr")), + c.setLocal("qr", c.getLocal("swp")), + + c.br(0) + ))); + + f.addCode(c.if( + c.getLocal("signt"), + c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))), + c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr")) + )); + } + + + buildCopy(); + buildZero(); + buildIsZero(); + buildOne(); + buildEq(); + buildGte(); + buildAdd(); + buildSub(); + buildMul(); + buildSquare(); + buildSquareOld(); + buildDiv(); + buildInverseMod(); + module.exportFunction(prefix+"_copy"); + module.exportFunction(prefix+"_zero"); + module.exportFunction(prefix+"_one"); + module.exportFunction(prefix+"_isZero"); + module.exportFunction(prefix+"_eq"); + module.exportFunction(prefix+"_gte"); + module.exportFunction(prefix+"_add"); + module.exportFunction(prefix+"_sub"); + module.exportFunction(prefix+"_mul"); + module.exportFunction(prefix+"_square"); + module.exportFunction(prefix+"_squareOld"); + module.exportFunction(prefix+"_div"); + module.exportFunction(prefix+"_inverseMod"); + + return prefix; +}; + + +/***/ }), + +/***/ 4911: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildMultiexp(module, prefix, fnName, opAdd, n8b) { + + const n64g = module.modules[prefix].n64; + const n8g = n64g*8; + + function buildGetChunk() { + const f = module.addFunction(fnName + "_getChunk"); + f.addParam("pScalar", "i32"); + f.addParam("scalarSize", "i32"); // Number of bytes of the scalar + f.addParam("startBit", "i32"); // Bit to start extract + f.addParam("chunkSize", "i32"); // Chunk size in bits + f.addLocal("bitsToEnd", "i32"); + f.addLocal("mask", "i32"); + f.setReturnType("i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("bitsToEnd", + c.i32_sub( + c.i32_mul( + c.getLocal("scalarSize"), + c.i32_const(8) + ), + c.getLocal("startBit") + ) + ), + c.if( + c.i32_gt_s( + c.getLocal("chunkSize"), + c.getLocal("bitsToEnd") + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("bitsToEnd") + ), + c.i32_const(1) + ) + ), + c.setLocal( + "mask", + c.i32_sub( + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ) + ), + c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("pScalar"), + c.i32_shr_u( + c.getLocal("startBit"), + c.i32_const(3) + ) + ), + 0, // offset + 0 // align to byte. + ), + c.i32_and( + c.getLocal("startBit"), + c.i32_const(0x7) + ) + ), + c.getLocal("mask") + ) + ); + } + + function buildMutiexpChunk() { + const f = module.addFunction(fnName + "_chunk"); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("startBit", "i32"); // bit where it starts the chunk + f.addParam("chunkSize", "i32"); // bit where it starts the chunk + f.addParam("pr", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("n")), + [ + ...c.call(prefix + "_zero", c.getLocal("pr")), + ...c.ret([]) + ] + ), + + // Allocate memory + + c.setLocal( + "nTable", + c.i32_shl( + c.i32_const(1), + c.getLocal("chunkSize") + ) + ), + c.setLocal("pTable", c.i32_load( c.i32_const(0) )), + c.i32_store( + c.i32_const(0), + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("nTable"), + c.i32_const(n8g) + ) + ) + ), + + // Reset Table + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("nTable") + ) + ), + + c.call( + prefix + "_zero", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("j"), + c.i32_const(n8g) + ) + ) + ), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + // Distribute elements + c.setLocal("itBase", c.getLocal("pBases")), + c.setLocal("itScalar", c.getLocal("pScalars")), + c.setLocal("endScalar", + c.i32_add( + c.getLocal("pScalars"), + c.i32_mul( + c.getLocal("n"), + c.getLocal("scalarSize") + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("itScalar"), + c.getLocal("endScalar") + ) + ), + + c.setLocal( + "idx", + c.call(fnName + "_getChunk", + c.getLocal("itScalar"), + c.getLocal("scalarSize"), + c.getLocal("startBit"), + c.getLocal("chunkSize") + ) + ), + + c.if( + c.getLocal("idx"), + [ + ...c.setLocal( + "pIdxTable", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.i32_sub( + c.getLocal("idx"), + c.i32_const(1) + ), + c.i32_const(n8g) + ) + ) + ), + ...c.call( + opAdd, + c.getLocal("pIdxTable"), + c.getLocal("itBase"), + c.getLocal("pIdxTable"), + ) + ] + ), + + c.setLocal("itScalar", c.i32_add(c.getLocal("itScalar"), c.getLocal("scalarSize"))), + c.setLocal("itBase", c.i32_add(c.getLocal("itBase"), c.i32_const(n8b))), + c.br(0) + )), + + c.call(fnName + "_reduceTable", c.getLocal("pTable"), c.getLocal("chunkSize")), + c.call( + prefix + "_copy", + c.getLocal("pTable"), + c.getLocal("pr") + ), + + + c.i32_store( + c.i32_const(0), + c.getLocal("pTable") + ) + + ); + } + + function buildMultiexp() { + const f = module.addFunction(fnName); + f.addParam("pBases", "i32"); + f.addParam("pScalars", "i32"); + f.addParam("scalarSize", "i32"); // Number of points + f.addParam("n", "i32"); // Number of points + f.addParam("pr", "i32"); + f.addLocal("chunkSize", "i32"); + f.addLocal("nChunks", "i32"); + f.addLocal("itScalar", "i32"); + f.addLocal("endScalar", "i32"); + f.addLocal("itBase", "i32"); + f.addLocal("itBit", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("nTable", "i32"); + f.addLocal("pTable", "i32"); + f.addLocal("idx", "i32"); + f.addLocal("pIdxTable", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8g)); + + const pTSizes = module.alloc([ + 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 16, 16, 15, 14, 13, 13, + 12, 11, 10, 9, 8, 7, 7, 6, + 5 , 4, 3, 2, 1, 1, 1, 1 + ]); + + f.addCode( + c.call(prefix + "_zero", c.getLocal("pr")), + c.if( + c.i32_eqz(c.getLocal("n")), + c.ret([]) + ), + c.setLocal("chunkSize", c.i32_load8_u( c.i32_clz(c.getLocal("n")), pTSizes )), + c.setLocal( + "nChunks", + c.i32_add( + c.i32_div_u( + c.i32_sub( + c.i32_shl( + c.getLocal("scalarSize"), + c.i32_const(3) + ), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ), + c.i32_const(1) + ) + ), + + + // Allocate memory + + c.setLocal( + "itBit", + c.i32_mul( + c.i32_sub( + c.getLocal("nChunks"), + c.i32_const(1) + ), + c.getLocal("chunkSize") + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_lt_s( + c.getLocal("itBit"), + c.i32_const(0) + ) + ), + + // Double nChunk times + c.if( + c.i32_eqz(c.call(prefix + "_isZero", c.getLocal("pr"))), + [ + ...c.setLocal("j", c.i32_const(0)), + ...c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("chunkSize") + ) + ), + + c.call(prefix + "_double", c.getLocal("pr"), c.getLocal("pr")), + + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )) + ] + ), + + c.call( + fnName + "_chunk", + c.getLocal("pBases"), + c.getLocal("pScalars"), + c.getLocal("scalarSize"), + c.getLocal("n"), + c.getLocal("itBit"), + c.getLocal("chunkSize"), + aux + ), + + c.call( + prefix + "_add", + c.getLocal("pr"), + aux, + c.getLocal("pr") + ), + c.setLocal("itBit", c.i32_sub(c.getLocal("itBit"), c.getLocal("chunkSize"))), + c.br(0) + )) + ); + } + + function buildReduceTable() { + const f = module.addFunction(fnName + "_reduceTable"); + f.addParam("pTable", "i32"); + f.addParam("p", "i32"); // Number of bits of the table + f.addLocal("half", "i32"); + f.addLocal("it1", "i32"); + f.addLocal("it2", "i32"); + f.addLocal("pAcc", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.if( + c.i32_eq(c.getLocal("p"), c.i32_const(1)), + c.ret([]) + ), + c.setLocal( + "half", + c.i32_shl( + c.i32_const(1), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ), + + c.setLocal("it1", c.getLocal("pTable")), + c.setLocal( + "it2", + c.i32_add( + c.getLocal("pTable"), + c.i32_mul( + c.getLocal("half"), + c.i32_const(n8g) + ) + ) + ), + c.setLocal("pAcc", + c.i32_sub( + c.getLocal("it2"), + c.i32_const(n8g) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it1"), + c.getLocal("pAcc") + ) + ), + c.call( + prefix + "_add", + c.getLocal("it1"), + c.getLocal("it2"), + c.getLocal("it1") + ), + c.call( + prefix + "_add", + c.getLocal("pAcc"), + c.getLocal("it2"), + c.getLocal("pAcc") + ), + c.setLocal("it1", c.i32_add(c.getLocal("it1"), c.i32_const(n8g))), + c.setLocal("it2", c.i32_add(c.getLocal("it2"), c.i32_const(n8g))), + c.br(0) + )), + + c.call( + fnName + "_reduceTable", + c.getLocal("pTable"), + c.i32_sub( + c.getLocal("p"), + c.i32_const(1) + ) + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.block(c.loop( + c.br_if(1, c.i32_eqz(c.getLocal("p"))), + c.call(prefix + "_double", c.getLocal("pAcc"), c.getLocal("pAcc")), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + )), + + c.call(prefix + "_add", c.getLocal("pTable"), c.getLocal("pAcc"), c.getLocal("pTable")) + ); + } + + buildGetChunk(); + buildReduceTable(); + buildMutiexpChunk(); + buildMultiexp(); + + module.exportFunction(fnName); + module.exportFunction(fnName +"_chunk"); + + +}; + + + + + +/***/ }), + +/***/ 2896: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildPol(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildZero() { + const f = module.addFunction(prefix+"_zero"); + f.addParam("px", "i32"); + f.addParam("n", "i32"); + f.addLocal("lastp", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("p", c.getLocal("px")), + c.setLocal( + "lastp", + c.i32_add( + c.getLocal("px"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("p"), + c.getLocal("lastp") + ) + ), + c.call(prefixField + "_zero", c.getLocal("p")), + c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildConstructLC() { + const f = module.addFunction(prefix+"_constructLC"); + f.addParam("ppolynomials", "i32"); + f.addParam("psignals", "i32"); + f.addParam("nSignals", "i32"); + f.addParam("pres", "i32"); + f.addLocal("i", "i32"); + f.addLocal("j", "i32"); + f.addLocal("pp", "i32"); + f.addLocal("ps", "i32"); + f.addLocal("pd", "i32"); + f.addLocal("ncoefs", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("i", c.i32_const(0)), + c.setLocal("pp", c.getLocal("ppolynomials")), + c.setLocal("ps", c.getLocal("psignals")), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("i"), + c.getLocal("nSignals") + ) + ), + + c.setLocal("ncoefs", c.i32_load(c.getLocal("pp"))), + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + c.setLocal("j", c.i32_const(0)), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("j"), + c.getLocal("ncoefs") + ) + ), + + c.setLocal( + "pd", + c.i32_add( + c.getLocal("pres"), + c.i32_mul( + c.i32_load(c.getLocal("pp")), + c.i32_const(n8) + ) + ) + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))), + + + c.call( + prefixField + "_mul", + c.getLocal("ps"), + c.getLocal("pp"), + aux + ), + + c.call( + prefixField + "_add", + aux, + c.getLocal("pd"), + c.getLocal("pd") + ), + + c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(n8))), + c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))), + c.br(0) + )), + + c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(n8))), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )) + ); + + } + + buildZero(); + buildConstructLC(); + + + module.exportFunction(prefix + "_zero"); + module.exportFunction(prefix + "_constructLC"); + + return prefix; + + + + +}; + + +/***/ }), + +/***/ 637: +/***/ ((module) => { + + +module.exports = function buildQAP(module, prefix, prefixField) { + + const n64 = module.modules[prefixField].n64; + const n8 = n64*8; + + + function buildBuildABC() { + const f = module.addFunction(prefix+"_buildABC"); + f.addParam("pCoefs", "i32"); + f.addParam("nCoefs", "i32"); + f.addParam("pWitness", "i32"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("offsetOut", "i32"); + f.addParam("nOut", "i32"); + f.addParam("offsetWitness", "i32"); + f.addParam("nWitness", "i32"); + f.addLocal("it", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("last", "i32"); + f.addLocal("m", "i32"); + f.addLocal("c", "i32"); + f.addLocal("s", "i32"); + f.addLocal("pOut", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + + // Set output a and b to 0 + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call(prefixField + "_zero", c.getLocal("ita")), + c.call(prefixField + "_zero", c.getLocal("itb")), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.br(0) + )), + + + c.setLocal("it", c.getLocal("pCoefs")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pCoefs"), + c.i32_mul( + c.getLocal("nCoefs"), + c.i32_const(n8+12) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("it"), + c.getLocal("last") + ) + ), + c.setLocal( + "s", + c.i32_load(c.getLocal("it"), 8) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("s"), + c.getLocal("offsetWitness"), + ), + c.i32_ge_u( + c.getLocal("s"), + c.i32_add( + c.getLocal("offsetWitness"), + c.getLocal("nWitness"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + + c.setLocal( + "m", + c.i32_load(c.getLocal("it")) + ), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(0)), + c.setLocal("pOut", c.getLocal("pA")), + c.if( + c.i32_eq(c.getLocal("m"), c.i32_const(1)), + c.setLocal("pOut", c.getLocal("pB")), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ) + ), + c.setLocal( + "c", + c.i32_load(c.getLocal("it"), 4) + ), + c.if( + c.i32_or( + c.i32_lt_u( + c.getLocal("c"), + c.getLocal("offsetOut"), + ), + c.i32_ge_u( + c.getLocal("c"), + c.i32_add( + c.getLocal("offsetOut"), + c.getLocal("nOut"), + ) + ) + ), + [ + ...c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + ...c.br(1) + ] + ), + c.setLocal( + "pOut", + c.i32_add( + c.getLocal("pOut"), + c.i32_mul( + c.i32_sub( + c.getLocal("c"), + c.getLocal("offsetOut") + ), + c.i32_const(n8) + ) + ) + ), + c.call( + prefixField + "_mul", + c.i32_add( + c.getLocal("pWitness"), + c.i32_mul( + c.i32_sub(c.getLocal("s"), c.getLocal("offsetWitness")), + c.i32_const(n8) + ) + ), + c.i32_add( c.getLocal("it"), c.i32_const(12)), + aux + ), + c.call( + prefixField + "_add", + c.getLocal("pOut"), + aux, + c.getLocal("pOut"), + ), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8+12))), + c.br(0) + )), + + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("it", c.getLocal("pC")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("nOut"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("it") + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("it", c.i32_add(c.getLocal("it"), c.i32_const(n8))), + c.br(0) + )), + + ); + } + + function buildJoinABC() { + const f = module.addFunction(prefix+"_joinABC"); + f.addParam("pA", "i32"); + f.addParam("pB", "i32"); + f.addParam("pC", "i32"); + f.addParam("n", "i32"); + f.addParam("pP", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itc", "i32"); + f.addLocal("itp", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(n8)); + + f.addCode( + c.setLocal("ita", c.getLocal("pA")), + c.setLocal("itb", c.getLocal("pB")), + c.setLocal("itc", c.getLocal("pC")), + c.setLocal("itp", c.getLocal("pP")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pA"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_mul", + c.getLocal("ita"), + c.getLocal("itb"), + aux + ), + c.call( + prefixField + "_sub", + aux, + c.getLocal("itc"), + c.getLocal("itp"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itc", c.i32_add(c.getLocal("itc"), c.i32_const(n8))), + c.setLocal("itp", c.i32_add(c.getLocal("itp"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + function buildBatchAdd() { + const f = module.addFunction(prefix+"_batchAdd"); + f.addParam("pa", "i32"); + f.addParam("pb", "i32"); + f.addParam("n", "i32"); + f.addParam("pr", "i32"); + f.addLocal("ita", "i32"); + f.addLocal("itb", "i32"); + f.addLocal("itr", "i32"); + f.addLocal("last", "i32"); + + const c = f.getCodeBuilder(); + + f.addCode( + c.setLocal("ita", c.getLocal("pa")), + c.setLocal("itb", c.getLocal("pb")), + c.setLocal("itr", c.getLocal("pr")), + c.setLocal( + "last", + c.i32_add( + c.getLocal("pa"), + c.i32_mul( + c.getLocal("n"), + c.i32_const(n8) + ) + ) + ), + c.block(c.loop( + c.br_if( + 1, + c.i32_eq( + c.getLocal("ita"), + c.getLocal("last") + ) + ), + c.call( + prefixField + "_add", + c.getLocal("ita"), + c.getLocal("itb"), + c.getLocal("itr"), + ), + c.setLocal("ita", c.i32_add(c.getLocal("ita"), c.i32_const(n8))), + c.setLocal("itb", c.i32_add(c.getLocal("itb"), c.i32_const(n8))), + c.setLocal("itr", c.i32_add(c.getLocal("itr"), c.i32_const(n8))), + c.br(0) + )) + ); + } + + buildBuildABC(); + buildJoinABC(); + buildBatchAdd(); + + module.exportFunction(prefix + "_buildABC"); + module.exportFunction(prefix + "_joinABC"); + module.exportFunction(prefix + "_batchAdd"); + + return prefix; + +}; + + + +/***/ }), + +/***/ 5107: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("i", "i32"); + f.addLocal("b", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ) + ); + f.addCode(c.call(opCopy, c.getLocal("base"), aux)); + f.addCode(c.call(opInit, c.getLocal("r"))); + f.addCode(c.setLocal("i", c.getLocal("scalarLength"))); + f.addCode(c.block(c.loop( + c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))), + + c.setLocal( + "b", + c.i32_load8_u( + c.i32_add( + c.getLocal("scalar"), + c.getLocal("i") + ) + ) + ), + ...innerLoop(), + c.br_if(1, c.i32_eqz ( c.getLocal("i") )), + c.br(0) + ))); + + + function innerLoop() { + const code = []; + for (let i=0; i<8; i++) { + code.push( + ...c.call(opAA, c.getLocal("r"), c.getLocal("r")), + ...c.if( + c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)), + [ + ...c.setLocal( + "b", + c.i32_sub( + c.getLocal("b"), + c.i32_const(0x80 >> i) + ) + ), + ...c.call(opAB, c.getLocal("r"),aux, c.getLocal("r")) + ] + ) + ); + } + return code; + } + +}; + + +/***/ }), + +/***/ 3972: +/***/ ((module) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +module.exports = function buildTimesScalarNAF(module, fnName, elementLen, opAB, opAA, opAmB, opCopy, opInit) { + + const f = module.addFunction(fnName); + f.addParam("base", "i32"); + f.addParam("scalar", "i32"); + f.addParam("scalarLength", "i32"); + f.addParam("r", "i32"); + f.addLocal("old0", "i32"); + f.addLocal("nbits", "i32"); + f.addLocal("i", "i32"); + f.addLocal("last", "i32"); + f.addLocal("cur", "i32"); + f.addLocal("carry", "i32"); + f.addLocal("p", "i32"); + + const c = f.getCodeBuilder(); + + const aux = c.i32_const(module.alloc(elementLen)); + + function getBit(IDX) { + return c.i32_and( + c.i32_shr_u( + c.i32_load( + c.i32_add( + c.getLocal("scalar"), + c.i32_and( + c.i32_shr_u( + IDX, + c.i32_const(3) + ), + c.i32_const(0xFFFFFFFC) + ) + ) + ), + c.i32_and( + IDX, + c.i32_const(0x1F) + ) + ), + c.i32_const(1) + ); + } + + function pushBit(b) { + return [ + ...c.i32_store8( + c.getLocal("p"), + c.i32_const(b) + ), + ...c.setLocal( + "p", + c.i32_add( + c.getLocal("p"), + c.i32_const(1) + ) + ) + ]; + } + + f.addCode( + c.if( + c.i32_eqz(c.getLocal("scalarLength")), + [ + ...c.call(opInit, c.getLocal("r")), + ...c.ret([]) + ] + ), + c.setLocal("nbits", c.i32_shl(c.getLocal("scalarLength"), c.i32_const(3))), + c.setLocal("old0", c.i32_load(c.i32_const(0))), + c.setLocal("p", c.getLocal("old0")), + c.i32_store( + c.i32_const(0), + c.i32_and( + c.i32_add( + c.i32_add( + c.getLocal("old0"), + c.i32_const(32) + ), + c.getLocal("nbits") + ), + c.i32_const(0xFFFFFFF8) + ) + ), + c.setLocal("i", c.i32_const(1)), + + c.setLocal("last",getBit(c.i32_const(0))), + c.setLocal("carry",c.i32_const(0)), + + c.block(c.loop( + c.br_if(1, c.i32_eq( c.getLocal("i"), c.getLocal("nbits"))), + + c.setLocal("cur", getBit(c.getLocal("i"))), + c.if( c.getLocal("last"), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(1) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(255) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(1) + ], + ), + ), + c.if( c.getLocal("cur"), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(1)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + c.if(c.getLocal("carry"), + [ + ...c.setLocal("last", c.i32_const(1)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ] + , + [ + ...c.setLocal("last", c.i32_const(0)), + ...c.setLocal("carry", c.i32_const(0)), + ...pushBit(0) + ], + ), + ) + ), + c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))), + c.br(0) + )), + + c.if( c.getLocal("last"), + c.if(c.getLocal("carry"), + [ + ...pushBit(255), + ...pushBit(0), + ...pushBit(1) + ] + , + [ + ...pushBit(1) + ], + ), + c.if(c.getLocal("carry"), + [ + ...pushBit(0), + ...pushBit(1) + ] + ), + ), + + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + + // p already points to the last bit + + c.call(opCopy, c.getLocal("base"), aux), + + c.call(opInit, c.getLocal("r")), + + c.block(c.loop( + + + c.call(opAA, c.getLocal("r"), c.getLocal("r")), + + + c.setLocal("cur", + c.i32_load8_u( + c.getLocal("p") + ) + ), + + c.if( + c.getLocal("cur"), + c.if( + c.i32_eq(c.getLocal("cur"), c.i32_const(1)), + c.call(opAB, c.getLocal("r"), aux, c.getLocal("r")), + c.call(opAmB, c.getLocal("r"), aux, c.getLocal("r")), + ) + ), + + c.br_if(1, c.i32_eq( c.getLocal("old0"), c.getLocal("p"))), + c.setLocal("p", c.i32_sub(c.getLocal("p"), c.i32_const(1))), + c.br(0) + + )), + + c.i32_store( c.i32_const(0), c.getLocal("old0")) + + ); + +}; + + +/***/ }), + +/***/ 2333: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + Copyright 2019 0KIMS association. + + This file is part of wasmsnark (Web Assembly zkSnark Prover). + + wasmsnark is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + wasmsnark is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with wasmsnark. If not, see . +*/ + +const bigInt = __webpack_require__(2096); + +exports.bigInt2BytesLE = function bigInt2BytesLE(_a, len) { + const b = Array(len); + let v = bigInt(_a); + for (let i=0; i { + +"use strict"; + + +var forEach = __webpack_require__(2682); +var availableTypedArrays = __webpack_require__(9209); +var callBind = __webpack_require__(487); +var callBound = __webpack_require__(8075); +var gOPD = __webpack_require__(5795); + +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(9092)(); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; + +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); +} + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; + + +/***/ }), + +/***/ 8982: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 7790: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 3776: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 1638: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2668: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 7965: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 6089: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9368: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 4688: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 1069: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 5340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 7882: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(6578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }), + +/***/ 3219: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}'); + +/***/ }), + +/***/ 2951: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}'); + +/***/ }), + +/***/ 4589: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}'); + +/***/ }), + +/***/ 3241: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}'); + +/***/ }), + +/***/ 1636: +/***/ ((module) => { + +"use strict"; +module.exports = {"rE":"6.5.5"}; + +/***/ }), + +/***/ 5579: +/***/ ((module) => { + +"use strict"; +module.exports = /*#__PURE__*/JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}'); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/amd options */ +/******/ (() => { +/******/ __webpack_require__.amdO = {}; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be in strict mode. +(() => { +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_native.js +var scalar_native_namespaceObject = {}; +__webpack_require__.r(scalar_native_namespaceObject); +__webpack_require__.d(scalar_native_namespaceObject, { + abs: () => (abs), + add: () => (add), + band: () => (band), + bitLength: () => (bitLength), + bits: () => (bits), + bor: () => (bor), + bxor: () => (bxor), + div: () => (div), + e: () => (e), + eq: () => (eq), + exp: () => (exp), + fromArray: () => (fromArray), + fromString: () => (fromString), + geq: () => (geq), + gt: () => (gt), + isNegative: () => (isNegative), + isOdd: () => (isOdd), + isZero: () => (isZero), + land: () => (land), + leq: () => (leq), + lnot: () => (lnot), + lor: () => (lor), + lt: () => (lt), + mod: () => (mod), + mul: () => (mul), + naf: () => (naf), + neg: () => (neg), + neq: () => (neq), + pow: () => (pow), + shiftLeft: () => (shiftLeft), + shiftRight: () => (shiftRight), + shl: () => (shl), + shr: () => (shr), + square: () => (square), + sub: () => (sub), + toArray: () => (toArray), + toNumber: () => (toNumber) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar_bigint.js +var scalar_bigint_namespaceObject = {}; +__webpack_require__.r(scalar_bigint_namespaceObject); +__webpack_require__.d(scalar_bigint_namespaceObject, { + abs: () => (scalar_bigint_abs), + add: () => (scalar_bigint_add), + band: () => (scalar_bigint_band), + bitLength: () => (scalar_bigint_bitLength), + bits: () => (scalar_bigint_bits), + bor: () => (scalar_bigint_bor), + bxor: () => (scalar_bigint_bxor), + div: () => (scalar_bigint_div), + e: () => (scalar_bigint_e), + eq: () => (scalar_bigint_eq), + exp: () => (scalar_bigint_exp), + fromArray: () => (scalar_bigint_fromArray), + fromString: () => (scalar_bigint_fromString), + geq: () => (scalar_bigint_geq), + gt: () => (scalar_bigint_gt), + isNegative: () => (scalar_bigint_isNegative), + isOdd: () => (scalar_bigint_isOdd), + isZero: () => (scalar_bigint_isZero), + land: () => (scalar_bigint_land), + leq: () => (scalar_bigint_leq), + lnot: () => (scalar_bigint_lnot), + lor: () => (scalar_bigint_lor), + lt: () => (scalar_bigint_lt), + mod: () => (scalar_bigint_mod), + mul: () => (scalar_bigint_mul), + naf: () => (scalar_bigint_naf), + neg: () => (scalar_bigint_neg), + neq: () => (scalar_bigint_neq), + pow: () => (scalar_bigint_pow), + shiftLeft: () => (scalar_bigint_shiftLeft), + shiftRight: () => (scalar_bigint_shiftRight), + shl: () => (scalar_bigint_shl), + shr: () => (scalar_bigint_shr), + square: () => (scalar_bigint_square), + sub: () => (scalar_bigint_sub), + toArray: () => (scalar_bigint_toArray), + toNumber: () => (scalar_bigint_toNumber) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/scalar.js +var scalar_namespaceObject = {}; +__webpack_require__.r(scalar_namespaceObject); +__webpack_require__.d(scalar_namespaceObject, { + abs: () => (scalar_abs), + add: () => (scalar_add), + band: () => (scalar_band), + bitLength: () => (scalar_bitLength), + bits: () => (scalar_bits), + bor: () => (scalar_bor), + bxor: () => (scalar_bxor), + div: () => (scalar_div), + e: () => (scalar_e), + eq: () => (scalar_eq), + exp: () => (scalar_exp), + fromArray: () => (scalar_fromArray), + fromRprBE: () => (fromRprBE), + fromRprLE: () => (fromRprLE), + fromString: () => (scalar_fromString), + geq: () => (scalar_geq), + gt: () => (scalar_gt), + isNegative: () => (scalar_isNegative), + isOdd: () => (scalar_isOdd), + isZero: () => (scalar_isZero), + land: () => (scalar_land), + leq: () => (scalar_leq), + lnot: () => (scalar_lnot), + lor: () => (scalar_lor), + lt: () => (scalar_lt), + mod: () => (scalar_mod), + mul: () => (scalar_mul), + naf: () => (scalar_naf), + neg: () => (scalar_neg), + neq: () => (scalar_neq), + one: () => (one), + pow: () => (scalar_pow), + shiftLeft: () => (scalar_shiftLeft), + shiftRight: () => (scalar_shiftRight), + shl: () => (scalar_shl), + shr: () => (scalar_shr), + square: () => (scalar_square), + sub: () => (scalar_sub), + toArray: () => (scalar_toArray), + toLEBuff: () => (toLEBuff), + toNumber: () => (scalar_toNumber), + toRprBE: () => (toRprBE), + toRprLE: () => (toRprLE), + toString: () => (scalar_toString), + zero: () => (zero) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_native.js +var utils_native_namespaceObject = {}; +__webpack_require__.r(utils_native_namespaceObject); +__webpack_require__.d(utils_native_namespaceObject, { + beBuff2int: () => (beBuff2int), + beInt2Buff: () => (beInt2Buff), + leBuff2int: () => (leBuff2int), + leInt2Buff: () => (leInt2Buff), + stringifyBigInts: () => (stringifyBigInts), + stringifyFElements: () => (stringifyFElements), + unstringifyBigInts: () => (unstringifyBigInts), + unstringifyFElements: () => (unstringifyFElements) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils_bigint.js +var utils_bigint_namespaceObject = {}; +__webpack_require__.r(utils_bigint_namespaceObject); +__webpack_require__.d(utils_bigint_namespaceObject, { + beBuff2int: () => (utils_bigint_beBuff2int), + beInt2Buff: () => (utils_bigint_beInt2Buff), + leBuff2int: () => (utils_bigint_leBuff2int), + leInt2Buff: () => (utils_bigint_leInt2Buff), + stringifyBigInts: () => (utils_bigint_stringifyBigInts), + unstringifyBigInts: () => (utils_bigint_unstringifyBigInts) +}); + +// NAMESPACE OBJECT: ./node_modules/ffjavascript/src/utils.js +var utils_namespaceObject = {}; +__webpack_require__.r(utils_namespaceObject); +__webpack_require__.d(utils_namespaceObject, { + array2buffer: () => (array2buffer), + beBuff2int: () => (utils_beBuff2int), + beInt2Buff: () => (utils_beInt2Buff), + bitReverse: () => (bitReverse), + buffReverseBits: () => (buffReverseBits), + buffer2array: () => (buffer2array), + leBuff2int: () => (utils_leBuff2int), + leInt2Buff: () => (utils_leInt2Buff), + log2: () => (utils_log2), + stringifyBigInts: () => (utils_stringifyBigInts), + stringifyFElements: () => (utils_stringifyFElements), + unstringifyBigInts: () => (utils_unstringifyBigInts), + unstringifyFElements: () => (utils_unstringifyFElements) +}); + +// EXTERNAL MODULE: worker_threads (ignored) +var worker_threads_ignored_ = __webpack_require__(7882); +var worker_threads_ignored_default = /*#__PURE__*/__webpack_require__.n(worker_threads_ignored_); +// EXTERNAL MODULE: ./node_modules/@tornado/fixed-merkle-tree/lib/index.js +var lib = __webpack_require__(1217); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_native.js +/* global BigInt */ +const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4]; + +function fromString(s, radix) { + if ((!radix)||(radix==10)) { + return BigInt(s); + } else if (radix==16) { + if (s.slice(0,2) == "0x") { + return BigInt(s); + } else { + return BigInt("0x"+s); + } + } +} + +const e = fromString; + +function fromArray(a, radix) { + let acc =BigInt(0); + radix = BigInt(radix); + for (let i=0; i> BigInt(n); +} + +const shl = shiftLeft; +const shr = shiftRight; + +function isOdd(a) { + return (BigInt(a) & BigInt(1)) == BigInt(1); +} + + +function naf(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + const z = 2 - Number(E % BigInt(4)); + res.push( z ); + E = E - BigInt(z); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + + +function bits(n) { + let E = BigInt(n); + const res = []; + while (E) { + if (E & BigInt(1)) { + res.push(1); + } else { + res.push( 0 ); + } + E = E >> BigInt(1); + } + return res; +} + +function toNumber(s) { + if (s>BigInt(Number.MAX_SAFE_INTEGER )) { + throw new Error("Number too big"); + } + return Number(s); +} + +function toArray(s, radix) { + const res = []; + let rem = BigInt(s); + radix = BigInt(radix); + while (rem) { + res.unshift( Number(rem % radix)); + rem = rem / radix; + } + return res; +} + + +function add(a, b) { + return BigInt(a) + BigInt(b); +} + +function sub(a, b) { + return BigInt(a) - BigInt(b); +} + +function neg(a) { + return -BigInt(a); +} + +function mul(a, b) { + return BigInt(a) * BigInt(b); +} + +function square(a) { + return BigInt(a) * BigInt(a); +} + +function pow(a, b) { + return BigInt(a) ** BigInt(b); +} + +function exp(a, b) { + return BigInt(a) ** BigInt(b); +} + +function abs(a) { + return BigInt(a) >= 0 ? BigInt(a) : -BigInt(a); +} + +function div(a, b) { + return BigInt(a) / BigInt(b); +} + +function mod(a, b) { + return BigInt(a) % BigInt(b); +} + +function eq(a, b) { + return BigInt(a) == BigInt(b); +} + +function neq(a, b) { + return BigInt(a) != BigInt(b); +} + +function lt(a, b) { + return BigInt(a) < BigInt(b); +} + +function gt(a, b) { + return BigInt(a) > BigInt(b); +} + +function leq(a, b) { + return BigInt(a) <= BigInt(b); +} + +function geq(a, b) { + return BigInt(a) >= BigInt(b); +} + +function band(a, b) { + return BigInt(a) & BigInt(b); +} + +function bor(a, b) { + return BigInt(a) | BigInt(b); +} + +function bxor(a, b) { + return BigInt(a) ^ BigInt(b); +} + +function land(a, b) { + return BigInt(a) && BigInt(b); +} + +function lor(a, b) { + return BigInt(a) || BigInt(b); +} + +function lnot(a) { + return !BigInt(a); +} + + +// EXTERNAL MODULE: ./node_modules/big-integer/BigInteger.js +var BigInteger = __webpack_require__(2096); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar_bigint.js + + +function scalar_bigint_fromString(s, radix) { + if (typeof s == "string") { + if (s.slice(0,2) == "0x") { + return BigInteger(s.slice(2), 16); + } else { + return BigInteger(s,radix); + } + } else { + return BigInteger(s, radix); + } +} + +const scalar_bigint_e = scalar_bigint_fromString; + +function scalar_bigint_fromArray(a, radix) { + return BigInteger.fromArray(a, radix); +} + +function scalar_bigint_bitLength(a) { + return BigInteger(a).bitLength(); +} + +function scalar_bigint_isNegative(a) { + return BigInteger(a).isNegative(); +} + +function scalar_bigint_isZero(a) { + return BigInteger(a).isZero(); +} + +function scalar_bigint_shiftLeft(a, n) { + return BigInteger(a).shiftLeft(n); +} + +function scalar_bigint_shiftRight(a, n) { + return BigInteger(a).shiftRight(n); +} + +const scalar_bigint_shl = scalar_bigint_shiftLeft; +const scalar_bigint_shr = scalar_bigint_shiftRight; + +function scalar_bigint_isOdd(a) { + return BigInteger(a).isOdd(); +} + + +function scalar_bigint_naf(n) { + let E = BigInteger(n); + const res = []; + while (E.gt(BigInteger.zero)) { + if (E.isOdd()) { + const z = 2 - E.mod(4).toJSNumber(); + res.push( z ); + E = E.minus(z); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function scalar_bigint_bits(n) { + let E = BigInteger(n); + const res = []; + while (E.gt(BigInteger.zero)) { + if (E.isOdd()) { + res.push(1); + } else { + res.push( 0 ); + } + E = E.shiftRight(1); + } + return res; +} + +function scalar_bigint_toNumber(s) { + if (!s.lt(BigInteger("9007199254740992", 10))) { + throw new Error("Number too big"); + } + return s.toJSNumber(); +} + +function scalar_bigint_toArray(s, radix) { + return BigInteger(s).toArray(radix); +} + +function scalar_bigint_add(a, b) { + return BigInteger(a).add(BigInteger(b)); +} + +function scalar_bigint_sub(a, b) { + return BigInteger(a).minus(BigInteger(b)); +} + +function scalar_bigint_neg(a) { + return BigInteger.zero.minus(BigInteger(a)); +} + +function scalar_bigint_mul(a, b) { + return BigInteger(a).times(BigInteger(b)); +} + +function scalar_bigint_square(a) { + return BigInteger(a).square(); +} + +function scalar_bigint_pow(a, b) { + return BigInteger(a).pow(BigInteger(b)); +} + +function scalar_bigint_exp(a, b) { + return BigInteger(a).pow(BigInteger(b)); +} + +function scalar_bigint_abs(a) { + return BigInteger(a).abs(); +} + +function scalar_bigint_div(a, b) { + return BigInteger(a).divide(BigInteger(b)); +} + +function scalar_bigint_mod(a, b) { + return BigInteger(a).mod(BigInteger(b)); +} + +function scalar_bigint_eq(a, b) { + return BigInteger(a).eq(BigInteger(b)); +} + +function scalar_bigint_neq(a, b) { + return BigInteger(a).neq(BigInteger(b)); +} + +function scalar_bigint_lt(a, b) { + return BigInteger(a).lt(BigInteger(b)); +} + +function scalar_bigint_gt(a, b) { + return BigInteger(a).gt(BigInteger(b)); +} + +function scalar_bigint_leq(a, b) { + return BigInteger(a).leq(BigInteger(b)); +} + +function scalar_bigint_geq(a, b) { + return BigInteger(a).geq(BigInteger(b)); +} + +function scalar_bigint_band(a, b) { + return BigInteger(a).and(BigInteger(b)); +} + +function scalar_bigint_bor(a, b) { + return BigInteger(a).or(BigInteger(b)); +} + +function scalar_bigint_bxor(a, b) { + return BigInteger(a).xor(BigInteger(b)); +} + +function scalar_bigint_land(a, b) { + return (!BigInteger(a).isZero()) && (!BigInteger(b).isZero()); +} + +function scalar_bigint_lor(a, b) { + return (!BigInteger(a).isZero()) || (!BigInteger(b).isZero()); +} + +function scalar_bigint_lnot(a) { + return BigInteger(a).isZero(); +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/scalar.js + + + + +const supportsNativeBigInt = typeof BigInt === "function"; + +let scalar_Scalar = {}; +if (supportsNativeBigInt) { + Object.assign(scalar_Scalar, scalar_native_namespaceObject); +} else { + Object.assign(scalar_Scalar, scalar_bigint_namespaceObject); +} + + +// Returns a buffer with Little Endian Representation +scalar_Scalar.toRprLE = function rprBE(buff, o, e, n8) { + const s = "0000000" + e.toString(16); + const v = new Uint32Array(buff.buffer, o, n8/4); + const l = (((s.length-7)*4 - 1) >> 5)+1; // Number of 32bit words; + for (let i=0; i> 5)+1; // Number of 32bit words; + for (let i=0; i a[a.length-i-1] = ch.toString(16).padStart(8,"0") ); + return scalar_Scalar.fromString(a.join(""), 16); +}; + +// Pases a buffer with Big Endian Representation +scalar_Scalar.fromRprBE = function rprLEM(buff, o, n8) { + n8 = n8 || buff.byteLength; + o = o || 0; + const v = new DataView(buff.buffer, buff.byteOffset + o, n8); + const a = new Array(n8/4); + for (let i=0; i. +*/ + +/* + This library does operations on polynomials with coefficients in a field F. + + A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented + by the array [ p0, p1, p2, ... , pn ]. + */ + +class PolField { + constructor (F) { + this.F = F; + + let rem = F.sqrt_t; + let s = F.sqrt_s; + + const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one); + + this.w = new Array(s+1); + this.wi = new Array(s+1); + this.w[s] = this.F.pow(five, rem); + this.wi[s] = this.F.inv(this.w[s]); + + let n=s-1; + while (n>=0) { + this.w[n] = this.F.square(this.w[n+1]); + this.wi[n] = this.F.square(this.wi[n+1]); + n--; + } + + + this.roots = []; +/* for (let i=0; i<16; i++) { + let r = this.F.one; + n = 1 << i; + const rootsi = new Array(n); + for (let j=0; j this.F.sqrt_s) n = this.s; + for (let i=n; (i>=0) && (!this.roots[i]); i--) { + let r = this.F.one; + const nroots = 1 << i; + const rootsi = new Array(nroots); + for (let j=0; j a.length) { + [b, a] = [a, b]; + } + + if ((b.length <= 2) || (b.length < log2(a.length))) { + return this.mulNormal(a,b); + } else { + return this.mulFFT(a,b); + } + } + + mulNormal(a, b) { + let res = []; + for (let i=0; i0) { + const z = new Array(n).fill(this.F.zero); + return z.concat(p); + } else { + if (-n >= p.length) return []; + return p.slice(-n); + } + } + + eval2(p, x) { + let v = this.F.zero; + let ix = this.F.one; + for (let i=0; i> 1), + F.mul( + x, + _eval(p, newX, offset+step , step << 1, n >> 1))); + return res; + } + } + + lagrange(points) { + let roots = [this.F.one]; + for (let i=0; i> 1; + const p1 = this._fft(pall, bits-1, offset, step*2); + const p2 = this._fft(pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + let m= this.F.one; + for (let i=0; i0 && this.F.eq(p[i], this.F.zero) ) i--; + return p.slice(0, i+1); + } + + eq(a, b) { + const pa = this.reduce(a); + const pb = this.reduce(b); + + if (pa.length != pb.length) return false; + for (let i=0; i=0; i--) { + res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]); + } + return res; + } + + _next2Power(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + toString(p) { + const ap = this.normalize(p); + let S = ""; + for (let i=ap.length-1; i>=0; i--) { + if (!this.F.eq(p[i], this.F.zero)) { + if (S!="") S += " + "; + S = S + p[i].toString(10); + if (i>0) { + S = S + "x"; + if (i>1) { + S = S + "^" +i; + } + } + } + } + return S; + } + + normalize(p) { + const res = new Array(p.length); + for (let i=0; i + // rec = x^(k-2-scaleV)/ v + // + // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v => + // res = rec * x^(m - (2*k-2 - scaleV)) => + // res = rec * x^(m - 2*k + 2 + scaleV) + + const rec = this._reciprocal(this.scaleX(v, scaleV), kbits); + const res = this.scaleX(rec, m - 2*k + 2 + scaleV); + + return res; + } + + div(_u, _v) { + if (_u.length < _v.length) return []; + const kbits = log2(_v.length-1)+1; + const k = 1 << kbits; + + const u = this.scaleX(_u, k-_v.length); + const v = this.scaleX(_v, k-_v.length); + + const n = v.length-1; + let m = u.length-1; + + const s = this._reciprocal(v, kbits); + let t; + if (m>2*n) { + t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v)); + } + + let q = []; + let rem = u; + let us, ut; + let finish = false; + + while (!finish) { + us = this.mul(rem, s); + q = this.add(q, this.scaleX(us, -2*n)); + + if ( m > 2*n ) { + ut = this.mul(rem, t); + rem = this.scaleX(ut, -2*n); + m = rem.length-1; + } else { + finish = true; + } + } + + return q; + } + + + // returns the ith nth-root of one + oneRoot(n, i) { + let nbits = log2(n-1)+1; + let res = this.F.one; + let r = i; + + if(i>=n) { + throw new Error("Given 'i' should be lower than 'n'"); + } + else if (1<0) { + if (r & 1 == 1) { + res = this.F.mul(res, this.w[nbits]); + } + r = r >> 1; + nbits --; + } + return res; + } + + computeVanishingPolinomial(bits, t) { + const m = 1 << bits; + return this.F.sub(this.F.pow(t, m), this.F.one); + } + + evaluateLagrangePolynomials(bits, t) { + const m= 1 << bits; + const tm = this.F.pow(t, m); + const u= new Array(m).fill(this.F.zero); + this._setRoots(bits); + const omega = this.w[bits]; + + if (this.F.eq(tm, this.F.one)) { + for (let i = 0; i < m; i++) { + if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i + u[i] = this.F.one; + return u; + } + } + } + + const z = this.F.sub(tm, this.F.one); + // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m)); + let l = this.F.mul(z, this.F.inv(this.F.e(m))); + for (let i = 0; i < m; i++) { + u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i]))); + l = this.F.mul(l, omega); + } + + return u; + } + + log2(V) { + return log2(V); + } +} + +function log2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +} + + +function __fft(PF, pall, bits, offset, step) { + + const n = 1 << bits; + if (n==1) { + return [ pall[offset] ]; + } else if (n==2) { + return [ + PF.F.add(pall[offset], pall[offset + step]), + PF.F.sub(pall[offset], pall[offset + step])]; + } + + const ndiv2 = n >> 1; + const p1 = __fft(PF, pall, bits-1, offset, step*2); + const p2 = __fft(PF, pall, bits-1, offset+step, step*2); + + const out = new Array(n); + + for (let i=0; i> 1; + const p1 = __fft2(PF, pall.slice(0, ndiv2), bits-1); + const p2 = __fft2(PF, pall.slice(ndiv2), bits-1); + + const out = new Array(n); + + for (let i=0; i>=1; + } + return res; +} + +function rev(idx, bits) { + return ( + _revTable[idx >>> 24] | + (_revTable[(idx >>> 16) & 0xFF] << 8) | + (_revTable[(idx >>> 8) & 0xFF] << 16) | + (_revTable[idx & 0xFF] << 24) + ) >>> (32-bits); +} + +function __bitReverse(p, bits) { + for (let k=0; kk) { + const tmp= p[k]; + p[k] = p[r]; + p[r] = tmp; + } + } + +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/futils.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + + +function mulScalar(F, base, e) { + let res; + + if (Scalar.isZero(e)) return F.zero; + + const n = Scalar.naf(e); + + if (n[n.length-1] == 1) { + res = base; + } else if (n[n.length-1] == -1) { + res = F.neg(base); + } else { + throw new Error("invlaud NAF"); + } + + for (let i=n.length-2; i>=0; i--) { + + res = F.double(res); + + if (n[i] == 1) { + res = F.add(res, base); + } else if (n[i] == -1) { + res = F.sub(res, base); + } + } + + return res; +} + + +/* +exports.mulScalar = (F, base, e) =>{ + let res = F.zero; + let rem = bigInt(e); + let exp = base; + + while (! rem.eq(bigInt.zero)) { + if (rem.and(bigInt.one).eq(bigInt.one)) { + res = F.add(res, exp); + } + exp = F.double(exp); + rem = rem.shiftRight(1); + } + + return res; +}; +*/ + + +function futils_exp(F, base, e) { + + if (scalar_isZero(e)) return F.one; + + const n = scalar_bits(e); + + if (n.legth==0) return F.one; + + let res = base; + + for (let i=n.length-2; i>=0; i--) { + + res = F.square(res); + + if (n[i]) { + res = F.mul(res, base); + } + } + + return res; +} + + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/fsqrt.js + +// Check here: https://eprint.iacr.org/2012/685.pdf + +function fsqrt_buildSqrt (F) { + if ((F.m % 2) == 1) { + if (scalar_eq(scalar_mod(F.p, 4), 1 )) { + if (scalar_eq(scalar_mod(F.p, 8), 1 )) { + if (scalar_eq(scalar_mod(F.p, 16), 1 )) { + // alg7_muller(F); + alg5_tonelliShanks(F); + } else if (scalar_eq(scalar_mod(F.p, 16), 9 )) { + alg4_kong(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (scalar_eq(scalar_mod(F.p, 8), 5 )) { + alg3_atkin(F); + } else { + throw new Error("Field withot sqrt"); + } + } else if (scalar_eq(scalar_mod(F.p, 4), 3 )) { + alg2_shanks(F); + } + } else { + const pm2mod4 = scalar_mod(scalar_pow(F.p, F.m/2), 4); + if (pm2mod4 == 1) { + alg10_adj(F); + } else if (pm2mod4 == 3) { + alg9_adj(F); + } else { + alg8_complex(F); + } + + } +} + + +function alg5_tonelliShanks(F) { + F.sqrt_q = scalar_pow(F.p, F.m); + + F.sqrt_s = 0; + F.sqrt_t = scalar_sub(F.sqrt_q, 1); + + while (!scalar_isOdd(F.sqrt_t)) { + F.sqrt_s = F.sqrt_s + 1; + F.sqrt_t = scalar_div(F.sqrt_t, 2); + } + + let c0 = F.one; + + while (F.eq(c0, F.one)) { + const c = F.random(); + F.sqrt_z = F.pow(c, F.sqrt_t); + c0 = F.pow(F.sqrt_z, 2 ** (F.sqrt_s-1) ); + } + + F.sqrt_tm1d2 = scalar_div(scalar_sub(F.sqrt_t, 1),2); + + F.sqrt = function(a) { + const F=this; + if (F.isZero(a)) return F.zero; + let w = F.pow(a, F.sqrt_tm1d2); + const a0 = F.pow( F.mul(F.square(w), a), 2 ** (F.sqrt_s-1) ); + if (F.eq(a0, F.negone)) return null; + + let v = F.sqrt_s; + let x = F.mul(a, w); + let b = F.mul(x, w); + let z = F.sqrt_z; + while (!F.eq(b, F.one)) { + let b2k = F.square(b); + let k=1; + while (!F.eq(b2k, F.one)) { + b2k = F.square(b2k); + k++; + } + + w = z; + for (let i=0; i>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 16) | ((st[d]>>>16) & 0xFFFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 12) | ((st[b]>>>20) & 0xFFF)) >>> 0; + + st[a] = (st[a] + st[b]) >>> 0; + st[d] = (st[d] ^ st[a]) >>> 0; + st[d] = ((st[d] << 8) | ((st[d]>>>24) & 0xFF)) >>> 0; + + st[c] = (st[c] + st[d]) >>> 0; + st[b] = (st[b] ^ st[c]) >>> 0; + st[b] = ((st[b] << 7) | ((st[b]>>>25) & 0x7F)) >>> 0; +} + +function doubleRound(st) { + quarterRound(st, 0, 4, 8,12); + quarterRound(st, 1, 5, 9,13); + quarterRound(st, 2, 6,10,14); + quarterRound(st, 3, 7,11,15); + + quarterRound(st, 0, 5,10,15); + quarterRound(st, 1, 6,11,12); + quarterRound(st, 2, 7, 8,13); + quarterRound(st, 3, 4, 9,14); +} + +class ChaCha { + + constructor(seed) { + seed = seed || [0,0,0,0,0,0,0,0]; + this.state = [ + 0x61707865, + 0x3320646E, + 0x79622D32, + 0x6B206574, + seed[0], + seed[1], + seed[2], + seed[3], + seed[4], + seed[5], + seed[6], + seed[7], + 0, + 0, + 0, + 0 + ]; + this.idx = 16; + this.buff = new Array(16); + } + + nextU32() { + if (this.idx == 16) this.update(); + return this.buff[this.idx++]; + } + + nextU64() { + return scalar_add(scalar_mul(this.nextU32(), 0x100000000), this.nextU32()); + } + + nextBool() { + return (this.nextU32() & 1) == 1; + } + + update() { + // Copy the state + for (let i=0; i<16; i++) this.buff[i] = this.state[i]; + + // Apply the rounds + for (let i=0; i<10; i++) doubleRound(this.buff); + + // Add to the initial + for (let i=0; i<16; i++) this.buff[i] = (this.buff[i] + this.state[i]) >>> 0; + + this.idx = 0; + + this.state[12] = (this.state[12] + 1) >>> 0; + if (this.state[12] != 0) return; + this.state[13] = (this.state[13] + 1) >>> 0; + if (this.state[13] != 0) return; + this.state[14] = (this.state[14] + 1) >>> 0; + if (this.state[14] != 0) return; + this.state[15] = (this.state[15] + 1) >>> 0; + } +} + +// EXTERNAL MODULE: ./node_modules/crypto-browserify/index.js +var crypto_browserify = __webpack_require__(1565); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/random.js +/* provided dependency */ var process = __webpack_require__(5606); + + + +function getRandomBytes(n) { + let array = new Uint8Array(n); + if (process.browser) { // Browser + if (typeof globalThis.crypto !== "undefined") { // Supported + globalThis.crypto.getRandomValues(array); + } else { // fallback + for (let i=0; i>>0; + } + } + } + else { // NodeJS + crypto_browserify.randomFillSync(array); + } + return array; +} + +function getRandomSeed() { + const arr = getRandomBytes(32); + const arrV = new Uint32Array(arr.buffer); + const seed = []; + for (let i=0; i<8; i++) { + seed.push(arrV[i]); + } + return seed; +} + +let threadRng = null; + +function getThreadRng() { + if (threadRng) return threadRng; + threadRng = new ChaCha(getRandomSeed()); + return threadRng; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_native.js +/* global BigInt */ + + + + + +class ZqField { + constructor(p) { + this.type="F1"; + this.one = BigInt(1); + this.zero = BigInt(0); + this.p = BigInt(p); + this.m = 1; + this.negone = this.p-this.one; + this.two = BigInt(2); + this.half = this.p >> this.one; + this.bitLength = scalar_bitLength(this.p); + this.mask = (this.one << BigInt(this.bitLength)) - this.one; + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = this.e(this.one << BigInt(this.n64*64)); + this.Ri = this.inv(this.R); + + const e = this.negone >> this.one; + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!this.eq(r, this.negone)) { + this.nqr = this.nqr + this.one; + r = this.pow(this.nqr, e); + } + + + this.s = 0; + this.t = this.negone; + + while ((this.t & this.one) == this.zero) { + this.s = this.s + 1; + this.t = this.t >> this.one; + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + fsqrt_buildSqrt(this); + } + + e(a,b) { + let res; + if (!b) { + res = BigInt(a); + } else if (b==16) { + res = BigInt("0x"+a); + } + if (res < 0) { + let nres = -res; + if (nres >= this.p) nres = nres % this.p; + return this.p - nres; + } else { + return (res>= this.p) ? res%this.p : res; + } + + } + + add(a, b) { + const res = a + b; + return res >= this.p ? res-this.p : res; + } + + sub(a, b) { + return (a >= b) ? a-b : this.p-b+a; + } + + neg(a) { + return a ? this.p-a : a; + } + + mul(a, b) { + return (a*b)%this.p; + } + + mulScalar(base, s) { + return (base * this.e(s)) % this.p; + } + + square(a) { + return (a*a) % this.p; + } + + eq(a, b) { + return a==b; + } + + neq(a, b) { + return a!=b; + } + + lt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa < bb; + } + + gt(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa > bb; + } + + leq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa <= bb; + } + + geq(a, b) { + const aa = (a > this.half) ? a - this.p : a; + const bb = (b > this.half) ? b - this.p : b; + return aa >= bb; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + idiv(a, b) { + if (!b) throw new Error("Division by zero"); + return a / b; + } + + inv(a) { + if (!a) throw new Error("Division by zero"); + + let t = this.zero; + let r = this.p; + let newt = this.one; + let newr = a % this.p; + while (newr) { + let q = r/newr; + [t, newt] = [newt, t-q*newt]; + [r, newr] = [newr, r-q*newr]; + } + if (t= this.p ? res-this.p : res; + } + + bor(a, b) { + const res = ((a | b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bxor(a, b) { + const res = ((a ^ b) & this.mask); + return res >= this.p ? res-this.p : res; + } + + bnot(a) { + const res = a ^ this.mask; + return res >= this.p ? res-this.p : res; + } + + shl(a, b) { + if (Number(b) < this.bitLength) { + const res = (a << b) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + return a >> nb; + } else { + return this.zero; + } + } + } + + shr(a, b) { + if (Number(b) < this.bitLength) { + return a >> b; + } else { + const nb = this.p - b; + if (Number(nb) < this.bitLength) { + const res = (a << nb) & this.mask; + return res >= this.p ? res-this.p : res; + } else { + return 0; + } + } + } + + land(a, b) { + return (a && b) ? this.one : this.zero; + } + + lor(a, b) { + return (a || b) ? this.one : this.zero; + } + + lnot(a) { + return (a) ? this.zero : this.one; + } + + sqrt_old(n) { + + if (n == this.zero) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone >> this.one); + if ( res != this.one ) return null; + + let m = this.s; + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one) >> this.one ); + + while ( t != this.one ) { + let sq = this.square(t); + let i = 1; + while (sq != this.one ) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r > (this.p >> this.one)) { + r = this.neg(r); + } + + return r; + } + + normalize(a, b) { + a = BigInt(a,b); + if (a < 0) { + let na = -a; + if (na >= this.p) na = na % this.p; + return this.p - na; + } else { + return (a>= this.p) ? a%this.p : a; + } + } + + random() { + const nBytes = (this.bitLength*2 / 8); + let res =this.zero; + for (let i=0; i this.half) { + const v = this.p-a; + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + return vs; + } + + isZero(a) { + return a == this.zero; + } + + fromRng(rng) { + let v; + do { + v=this.zero; + for (let i=0; i= this.p); + v = (v * this.Ri) % this.p; // Convert from montgomery + return v; + } + +} + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f1field_bigint.js + + + + +class f1field_bigint_ZqField { + constructor(p) { + this.type="F1"; + this.one = BigInteger.one; + this.zero = BigInteger.zero; + this.p = BigInteger(p); + this.m = 1; + this.negone = this.p.minus(BigInteger.one); + this.two = BigInteger(2); + this.half = this.p.shiftRight(1); + this.bitLength = this.p.bitLength(); + this.mask = BigInteger.one.shiftLeft(this.bitLength).minus(BigInteger.one); + + this.n64 = Math.floor((this.bitLength - 1) / 64)+1; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + this.R = BigInteger.one.shiftLeft(this.n64*64); + this.Ri = this.inv(this.R); + + const e = this.negone.shiftRight(this.one); + this.nqr = this.two; + let r = this.pow(this.nqr, e); + while (!r.equals(this.negone)) { + this.nqr = this.nqr.add(this.one); + r = this.pow(this.nqr, e); + } + + this.s = this.zero; + this.t = this.negone; + + while (!this.t.isOdd()) { + this.s = this.s.add(this.one); + this.t = this.t.shiftRight(this.one); + } + + this.nqr_to_t = this.pow(this.nqr, this.t); + + fsqrt_buildSqrt(this); + } + + e(a,b) { + + const res = BigInteger(a,b); + + return this.normalize(res); + + } + + add(a, b) { + let res = a.add(b); + if (res.geq(this.p)) { + res = res.minus(this.p); + } + return res; + } + + sub(a, b) { + if (a.geq(b)) { + return a.minus(b); + } else { + return this.p.minus(b.minus(a)); + } + } + + neg(a) { + if (a.isZero()) return a; + return this.p.minus(a); + } + + mul(a, b) { + return a.times(b).mod(this.p); + } + + mulScalar(base, s) { + return base.times(BigInteger(s)).mod(this.p); + } + + square(a) { + return a.square().mod(this.p); + } + + eq(a, b) { + return a.eq(b); + } + + neq(a, b) { + return a.neq(b); + } + + lt(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.lt(bb); + } + + gt(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.gt(bb); + } + + leq(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.leq(bb); + } + + geq(a, b) { + const aa = a.gt(this.half) ? a.minus(this.p) : a; + const bb = b.gt(this.half) ? b.minus(this.p) : b; + return aa.geq(bb); + } + + div(a, b) { + if (b.isZero()) throw new Error("Division by zero"); + return a.times(b.modInv(this.p)).mod(this.p); + } + + idiv(a, b) { + if (b.isZero()) throw new Error("Division by zero"); + return a.divide(b); + } + + inv(a) { + if (a.isZero()) throw new Error("Division by zero"); + return a.modInv(this.p); + } + + mod(a, b) { + return a.mod(b); + } + + pow(a, b) { + return a.modPow(b, this.p); + } + + exp(a, b) { + return a.modPow(b, this.p); + } + + band(a, b) { + return a.and(b).and(this.mask).mod(this.p); + } + + bor(a, b) { + return a.or(b).and(this.mask).mod(this.p); + } + + bxor(a, b) { + return a.xor(b).and(this.mask).mod(this.p); + } + + bnot(a) { + return a.xor(this.mask).mod(this.p); + } + + shl(a, b) { + if (b.lt(this.bitLength)) { + return a.shiftLeft(b).and(this.mask).mod(this.p); + } else { + const nb = this.p.minus(b); + if (nb.lt(this.bitLength)) { + return this.shr(a, nb); + } else { + return BigInteger.zero; + } + } + } + + shr(a, b) { + if (b.lt(this.bitLength)) { + return a.shiftRight(b); + } else { + const nb = this.p.minus(b); + if (nb.lt(this.bitLength)) { + return this.shl(a, nb); + } else { + return BigInteger.zero; + } + } + } + + land(a, b) { + return (a.isZero() || b.isZero()) ? BigInteger.zero : BigInteger.one; + } + + lor(a, b) { + return (a.isZero() && b.isZero()) ? BigInteger.zero : BigInteger.one; + } + + lnot(a) { + return a.isZero() ? BigInteger.one : BigInteger.zero; + } + + sqrt_old(n) { + + if (n.equals(this.zero)) return this.zero; + + // Test that have solution + const res = this.pow(n, this.negone.shiftRight(this.one)); + if (!res.equals(this.one)) return null; + + let m = parseInt(this.s); + let c = this.nqr_to_t; + let t = this.pow(n, this.t); + let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) ); + + while (!t.equals(this.one)) { + let sq = this.square(t); + let i = 1; + while (!sq.equals(this.one)) { + i++; + sq = this.square(sq); + } + + // b = c ^ m-i-1 + let b = c; + for (let j=0; j< m-i-1; j ++) b = this.square(b); + + m = i; + c = this.square(b); + t = this.mul(t, c); + r = this.mul(r, b); + } + + if (r.greater(this.p.shiftRight(this.one))) { + r = this.neg(r); + } + + return r; + } + + normalize(a) { + a = BigInteger(a); + if (a.isNegative()) { + return this.p.minus(a.abs().mod(this.p)); + } else { + return a.mod(this.p); + } + } + + random() { + let res = BigInteger(0); + let n = BigInteger(this.p.square()); + while (!n.isZero()) { + res = res.shiftLeft(8).add(BigInteger(getRandomBytes(1)[0])); + n = n.shiftRight(8); + } + return res.mod(this.p); + } + + toString(a, base) { + let vs; + if (!a.lesserOrEquals(this.p.shiftRight(BigInteger(1)))) { + const v = this.p.minus(a); + vs = "-"+v.toString(base); + } else { + vs = a.toString(base); + } + + return vs; + } + + isZero(a) { + return a.isZero(); + } + + fromRng(rng) { + let v; + do { + v = BigInteger(0); + for (let i=0; i. +*/ + + + + +class F2Field { + constructor(F, nonResidue) { + this.type="F2"; + this.F = F; + this.zero = [this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*2; + this.p = F.p; + this.n64 = F.n64*2; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + + buildSqrt(this); + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + conjugate(a) { + return [ + a[0], + this.F.neg(a[1]) + ]; + } + + mul(a, b) { + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + + return [ + this.F.add( aA , this._mulByNonResidue(bB)), + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB))]; + } + + inv(a) { + const t0 = this.F.square(a[0]); + const t1 = this.F.square(a[1]); + const t2 = this.F.sub(t0, this._mulByNonResidue(t1)); + const t3 = this.F.inv(t2); + return [ + this.F.mul(a[0], t3), + this.F.neg(this.F.mul( a[1], t3)) ]; + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const ab = this.F.mul(a[0] , a[1]); + + /* + [ + (a + b) * (a + non_residue * b) - ab - non_residue * ab, + ab + ab + ]; + */ + + return [ + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]) , + this.F.add( + a[0] , + this._mulByNonResidue(a[1]))), + this.F.add( + ab, + this._mulByNonResidue(ab))), + this.F.add(ab, ab) + ]; + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]); + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + pow(base, e) { + return fUtils.exp(this, base, e); + } + + exp(base, e) { + return fUtils.exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + return [c0, c1]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + return false; + } + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[1]); + this.F.toRprBE(buff, o+this.F.n8, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[1]); + this.F.toRprBEM(buff, o+this.F.n8, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBE(buff, o); + const c0 = this.F.fromRprBE(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.F.n8); + return [c0, c1]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c1 = this.F.fromRprBEM(buff, o); + const c0 = this.F.fromRprBEM(buff, o+this.F.n8); + return [c0, c1]; + } + +} + + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/f3field.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + +class F3Field { + constructor(F, nonResidue) { + this.type="F3"; + this.F = F; + this.zero = [this.F.zero, this.F.zero, this.F.zero]; + this.one = [this.F.one, this.F.zero, this.F.zero]; + this.negone = this.neg(this.one); + this.nonResidue = nonResidue; + this.m = F.m*3; + this.p = F.p; + this.n64 = F.n64*3; + this.n32 = this.n64*2; + this.n8 = this.n64*8; + } + + _mulByNonResidue(a) { + return this.F.mul(this.nonResidue, a); + } + + copy(a) { + return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])]; + } + + add(a, b) { + return [ + this.F.add(a[0], b[0]), + this.F.add(a[1], b[1]), + this.F.add(a[2], b[2]) + ]; + } + + double(a) { + return this.add(a,a); + } + + sub(a, b) { + return [ + this.F.sub(a[0], b[0]), + this.F.sub(a[1], b[1]), + this.F.sub(a[2], b[2]) + ]; + } + + neg(a) { + return this.sub(this.zero, a); + } + + mul(a, b) { + + const aA = this.F.mul(a[0] , b[0]); + const bB = this.F.mul(a[1] , b[1]); + const cC = this.F.mul(a[2] , b[2]); + + return [ + this.F.add( + aA, + this._mulByNonResidue( + this.F.sub( + this.F.mul( + this.F.add(a[1], a[2]), + this.F.add(b[1], b[2])), + this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC), + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[1]), + this.F.add(b[0], b[1])), + this.F.add(aA, bB)), + this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC + + this.F.add( + this.F.sub( + this.F.mul( + this.F.add(a[0], a[2]), + this.F.add(b[0], b[2])), + this.F.add(aA, cC)), + bB)]; // (a+c)*(A+C)-aA+bB-cC) + } + + inv(a) { + const t0 = this.F.square(a[0]); // t0 = a^2 ; + const t1 = this.F.square(a[1]); // t1 = b^2 ; + const t2 = this.F.square(a[2]); // t2 = c^2; + const t3 = this.F.mul(a[0],a[1]); // t3 = ab + const t4 = this.F.mul(a[0],a[2]); // t4 = ac + const t5 = this.F.mul(a[1],a[2]); // t5 = bc; + // c0 = t0 - non_residue * t5; + const c0 = this.F.sub(t0, this._mulByNonResidue(t5)); + // c1 = non_residue * t2 - t3; + const c1 = this.F.sub(this._mulByNonResidue(t2), t3); + const c2 = this.F.sub(t1, t4); // c2 = t1-t4 + + // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv(); + const t6 = + this.F.inv( + this.F.add( + this.F.mul(a[0], c0), + this._mulByNonResidue( + this.F.add( + this.F.mul(a[2], c1), + this.F.mul(a[1], c2))))); + + return [ + this.F.mul(t6, c0), // t6*c0 + this.F.mul(t6, c1), // t6*c1 + this.F.mul(t6, c2)]; // t6*c2 + } + + div(a, b) { + return this.mul(a, this.inv(b)); + } + + square(a) { + const s0 = this.F.square(a[0]); // s0 = a^2 + const ab = this.F.mul(a[0], a[1]); // ab = a*b + const s1 = this.F.add(ab, ab); // s1 = 2ab; + const s2 = this.F.square( + this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2; + const bc = this.F.mul(a[1],a[2]); // bc = b*c + const s3 = this.F.add(bc, bc); // s3 = 2*bc + const s4 = this.F.square(a[2]); // s4 = c^2 + + + return [ + this.F.add( + s0, + this._mulByNonResidue(s3)), // s0 + non_residue * s3, + this.F.add( + s1, + this._mulByNonResidue(s4)), // s1 + non_residue * s4, + this.F.sub( + this.F.add( this.F.add(s1, s2) , s3 ), + this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4 + } + + isZero(a) { + return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]); + } + + eq(a, b) { + return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]); + } + + affine(a) { + return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])]; + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + pow(base, e) { + return fUtils.exp(this, base, e); + } + + exp(base, e) { + return fUtils.exp(this, base, e); + } + + toString(a) { + return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`; + } + + fromRng(rng) { + const c0 = this.F.fromRng(rng); + const c1 = this.F.fromRng(rng); + const c2 = this.F.fromRng(rng); + return [c0, c1, c2]; + } + + gt(a, b) { + if (this.F.gt(a[0], b[0])) return true; + if (this.F.gt(b[0], a[0])) return false; + if (this.F.gt(a[1], b[1])) return true; + if (this.F.gt(b[1], a[1])) return false; + if (this.F.gt(a[2], b[2])) return true; + return false; + } + + + geq(a, b) { + return this.gt(a, b) || this.eq(a, b); + } + + lt(a, b) { + return !this.geq(a,b); + } + + leq(a, b) { + return !this.gt(a,b); + } + + neq(a, b) { + return !this.eq(a,b); + } + + random() { + return [this.F.random(), this.F.random(), this.F.random()]; + } + + + toRprLE(buff, o, e) { + this.F.toRprLE(buff, o, e[0]); + this.F.toRprLE(buff, o+this.F.n8, e[1]); + this.F.toRprLE(buff, o+this.F.n8*2, e[2]); + } + + toRprBE(buff, o, e) { + this.F.toRprBE(buff, o, e[2]); + this.F.toRprBE(buff, o+this.F.n8, e[1]); + this.F.toRprBE(buff, o+this.F.n8*2, e[0]); + } + + toRprLEM(buff, o, e) { + this.F.toRprLEM(buff, o, e[0]); + this.F.toRprLEM(buff, o+this.F.n8, e[1]); + this.F.toRprLEM(buff, o+this.F.n8*2, e[2]); + } + + + toRprBEM(buff, o, e) { + this.F.toRprBEM(buff, o, e[2]); + this.F.toRprBEM(buff, o+this.F.n8, e[1]); + this.F.toRprBEM(buff, o+this.F.n8*2, e[0]); + } + + fromRprLE(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLE(buff, o); + const c1 = this.F.fromRprLE(buff, o+this.n8); + const c2 = this.F.fromRprLE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBE(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBE(buff, o); + const c1 = this.F.fromRprBE(buff, o+this.n8); + const c0 = this.F.fromRprBE(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const c0 = this.F.fromRprLEM(buff, o); + const c1 = this.F.fromRprLEM(buff, o+this.n8); + const c2 = this.F.fromRprLEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const c2 = this.F.fromRprBEM(buff, o); + const c1 = this.F.fromRprBEM(buff, o+this.n8); + const c0 = this.F.fromRprBEM(buff, o+this.n8*2); + return [c0, c1, c2]; + } + +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/ec.js +/* + Copyright 2018 0kims association. + + This file is part of snarkjs. + + snarkjs is a free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or (at your option) + any later version. + + snarkjs is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along with + snarkjs. If not, see . +*/ + + + + + + + +function isGreatest(F, a) { + if (Array.isArray(a)) { + for (let i=a.length-1; i>=0; i--) { + if (!F.F.isZero(a[i])) { + return isGreatest(F.F, a[i]); + } + } + return 0; + } else { + const na = F.neg(a); + return Scalar.gt(a, na); + } +} + + +class EC { + + constructor(F, g) { + this.F = F; + this.g = g; + if (this.g.length == 2) this.g[2] = this.F.one; + this.zero = [this.F.zero, this.F.one, this.F.zero]; + } + + add(p1, p2) { + + const F = this.F; + + if (this.eq(p1, this.zero)) return p2; + if (this.eq(p2, this.zero)) return p1; + + const res = new Array(3); + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2 + const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1 + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2 + const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1 + + if (F.eq(U1,U2) && F.eq(S1,S2)) { + return this.double(p1); + } + + const H = F.sub( U2 , U1 ); // H = U2-U1 + + const S2_minus_S1 = F.sub( S2 , S1 ); + + const I = F.square( F.add(H,H) ); // I = (2 * H)^2 + const J = F.mul( H , I ); // J = H * I + + const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1) + const V = F.mul( U1 , I ); // V = U1 * I + + res[0] = + F.sub( + F.sub( F.square(r) , J ), + F.add( V , V )); // X3 = r^2 - J - 2 * V + + const S1_J = F.mul( S1 , J ); + + res[1] = + F.sub( + F.mul( r , F.sub(V,res[0])), + F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J + + res[2] = + F.mul( + H, + F.sub( + F.square( F.add(p1[2],p2[2]) ), + F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H + + return res; + } + + neg(p) { + return [p[0], this.F.neg(p[1]), p[2]]; + } + + sub(a, b) { + return this.add(a, this.neg(b)); + } + + double(p) { + const F = this.F; + + const res = new Array(3); + + if (this.eq(p, this.zero)) return p; + + const A = F.square( p[0] ); // A = X1^2 + const B = F.square( p[1] ); // B = Y1^2 + const C = F.square( B ); // C = B^2 + + let D = + F.sub( + F.square( F.add(p[0] , B )), + F.add( A , C)); + D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C) + + const E = F.add( F.add(A,A), A); // E = 3 * A + const FF =F.square( E ); // F = E^2 + + res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D + + let eightC = F.add( C , C ); + eightC = F.add( eightC , eightC ); + eightC = F.add( eightC , eightC ); + + res[1] = + F.sub( + F.mul( + E, + F.sub( D, res[0] )), + eightC); // Y3 = E * (D - X3) - 8 * C + + const Y1Z1 = F.mul( p[1] , p[2] ); + res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1 + + return res; + } + + timesScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + mulScalar(base, e) { + return fUtils.mulScalar(this, base, e); + } + + affine(p) { + const F = this.F; + if (this.isZero(p)) { + return this.zero; + } else if (F.eq(p[2], F.one)) { + return p; + } else { + const Z_inv = F.inv(p[2]); + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + const res = new Array(3); + res[0] = F.mul(p[0],Z2_inv); + res[1] = F.mul(p[1],Z3_inv); + res[2] = F.one; + + return res; + } + } + + multiAffine(arr) { + const keys = Object.keys(arr); + const F = this.F; + const accMul = new Array(keys.length+1); + accMul[0] = F.one; + for (let i = 0; i< keys.length; i++) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i+1] = accMul[i]; + } else { + accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]); + } + } + + accMul[keys.length] = F.inv(accMul[keys.length]); + + for (let i = keys.length-1; i>=0; i--) { + if (F.eq(arr[keys[i]][2], F.zero)) { + accMul[i] = accMul[i+1]; + arr[keys[i]] = this.zero; + } else { + const Z_inv = F.mul(accMul[i], accMul[i+1]); + accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]); + + const Z2_inv = F.square(Z_inv); + const Z3_inv = F.mul(Z2_inv, Z_inv); + + arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv); + arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv); + arr[keys[i]][2] = F.one; + } + } + + } + + eq(p1, p2) { + const F = this.F; + + if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero); + if (this.F.eq(p2[2], this.F.zero)) return false; + + const Z1Z1 = F.square( p1[2] ); + const Z2Z2 = F.square( p2[2] ); + + const U1 = F.mul( p1[0] , Z2Z2 ); + const U2 = F.mul( p2[0] , Z1Z1 ); + + const Z1_cubed = F.mul( p1[2] , Z1Z1); + const Z2_cubed = F.mul( p2[2] , Z2Z2); + + const S1 = F.mul( p1[1] , Z2_cubed); + const S2 = F.mul( p2[1] , Z1_cubed); + + return (F.eq(U1,U2) && F.eq(S1,S2)); + } + + isZero(p) { + return this.F.isZero(p[2]); + } + + toString(p) { + const cp = this.affine(p); + return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`; + } + + fromRng(rng) { + const F = this.F; + let P = []; + let greatest; + do { + P[0] = F.fromRng(rng); + greatest = rng.nextBool(); + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + } while ((P[1] == null)||(F.isZero[P])); + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + if (this.cofactor) { + P = this.mulScalar(P, this.cofactor); + } + + P = this.affine(P); + + return P; + + } + + toRprLE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLE(buff, o, p[0]); + this.F.toRprLE(buff, o+this.F.n8, p[1]); + } + + toRprBE(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBE(buff, o, p[0]); + this.F.toRprBE(buff, o+this.F.n8, p[1]); + } + + toRprLEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + } + + toRprLEJM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprLEM(buff, o, p[0]); + this.F.toRprLEM(buff, o+this.F.n8, p[1]); + this.F.toRprLEM(buff, o+2*this.F.n8, p[2]); + } + + + toRprBEM(buff, o, p) { + p = this.affine(p); + if (this.isZero(p)) { + const BuffV = new Uint8Array(buff, o, this.F.n8*2); + BuffV.fill(0); + return; + } + this.F.toRprBEM(buff, o, p[0]); + this.F.toRprBEM(buff, o+this.F.n8, p[1]); + } + + fromRprLE(buff, o) { + o = o || 0; + const x = this.F.fromRprLE(buff, o); + const y = this.F.fromRprLE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprBE(buff, o) { + o = o || 0; + const x = this.F.fromRprBE(buff, o); + const y = this.F.fromRprBE(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprLEJM(buff, o) { + o = o || 0; + const x = this.F.fromRprLEM(buff, o); + const y = this.F.fromRprLEM(buff, o+this.F.n8); + const z = this.F.fromRprLEM(buff, o+this.F.n8*2); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, z]; + } + + fromRprBEM(buff, o) { + o = o || 0; + const x = this.F.fromRprBEM(buff, o); + const y = this.F.fromRprBEM(buff, o+this.F.n8); + if (this.F.isZero(x) && this.F.isZero(y)) { + return this.zero; + } + return [x, y, this.F.one]; + } + + fromRprCompressed(buff, o) { + const F = this.F; + const v = new Uint8Array(buff.buffer, o, F.n8); + if (v[0] & 0x40) return this.zero; + const P = new Array(3); + + const greatest = ((v[0] & 0x80) != 0); + v[0] = v[0] & 0x7F; + P[0] = F.fromRprBE(buff, o); + if (greatest) v[0] = v[0] | 0x80; // set back again the old value + + const x3b = F.add(F.mul(F.square(P[0]), P[0]), this.b); + P[1] = F.sqrt(x3b); + + if (P[1] === null) { + throw new Error("Invalid Point!"); + } + + const s = isGreatest(F, P[1]); + if (greatest ^ s) P[1] = F.neg(P[1]); + P[2] = F.one; + + return P; + } + + toRprCompressed(buff, o, p) { + p = this.affine(p); + const v = new Uint8Array(buff.buffer, o, this.F.n8); + if (this.isZero(p)) { + v.fill(0); + v[0] = 0x40; + return; + } + this.F.toRprBE(buff, o, p[0]); + + if (isGreatest(this.F, p[1])) { + v[0] = v[0] | 0x80; + } + } + + + fromRprUncompressed(buff, o) { + if (buff[0] & 0x40) return this.zero; + + return this.fromRprBE(buff, o); + } + + toRprUncompressed(buff, o, p) { + this.toRprBE(buff, o, p); + + if (this.isZero(p)) { + buff[o] = buff[o] | 0x40; + } + } + + +} + + + +// EXTERNAL MODULE: ./node_modules/wasmcurves/index.js +var wasmcurves = __webpack_require__(189); +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_native.js +/* global BigInt */ + + +function stringifyBigInts(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return fromRprLE(o, 0); + } else if (Array.isArray(o)) { + return o.map(stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return BigInt(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return BigInt(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyBigInts); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function beBuff2int(buff) { + let res = BigInt(0); + let i = buff.length; + let offset = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i>0) { + if (i >= 4) { + i -= 4; + res += BigInt(buffV.getUint32(i)) << BigInt(offset*8); + offset += 4; + } else if (i >= 2) { + i -= 2; + res += BigInt(buffV.getUint16(i)) << BigInt(offset*8); + offset += 2; + } else { + i -= 1; + res += BigInt(buffV.getUint8(i)) << BigInt(offset*8); + offset += 1; + } + } + return res; +} + +function beInt2Buff(n, len) { + let r = n; + const buff = new Uint8Array(len); + const buffV = new DataView(buff.buffer); + let o = len; + while (o > 0) { + if (o-4 >= 0) { + o -= 4; + buffV.setUint32(o, Number(r & BigInt(0xFFFFFFFF))); + r = r >> BigInt(32); + } else if (o-2 >= 0) { + o -= 2; + buffV.setUint16(o, Number(r & BigInt(0xFFFF))); + r = r >> BigInt(16); + } else { + o -= 1; + buffV.setUint8(o, Number(r & BigInt(0xFF))); + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function leBuff2int(buff) { + let res = BigInt(0); + let i = 0; + const buffV = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); + while (i> BigInt(32); + } else if (o+2 <= len) { + buffV.setUint16(Number(o, r & BigInt(0xFFFF)), true ); + o += 2; + r = r >> BigInt(16); + } else { + buffV.setUint8(Number(o, r & BigInt(0xFF)), true ); + o += 1; + r = r >> BigInt(8); + } + } + if (r) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function stringifyFElements(F, o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (o instanceof Uint8Array) { + return F.toString(F.e(o)); + } else if (Array.isArray(o)) { + return o.map(stringifyFElements.bind(this,F)); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = stringifyFElements(F, o[k]); + }); + return res; + } else { + return o; + } +} + + +function unstringifyFElements(F, o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return F.e(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return F.e(o); + } else if (Array.isArray(o)) { + return o.map(unstringifyFElements.bind(this,F)); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = unstringifyFElements(F, o[k]); + }); + return res; + } else { + return o; + } +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/utils_bigint.js + + +function utils_bigint_stringifyBigInts(o) { + if ((typeof(o) == "bigint") || o.eq !== undefined) { + return o.toString(10); + } else if (Array.isArray(o)) { + return o.map(utils_bigint_stringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = utils_bigint_stringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function utils_bigint_unstringifyBigInts(o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return BigInteger(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return BigInteger(o); + } else if (Array.isArray(o)) { + return o.map(utils_bigint_unstringifyBigInts); + } else if (typeof o == "object") { + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = utils_bigint_unstringifyBigInts(o[k]); + }); + return res; + } else { + return o; + } +} + +function utils_bigint_beBuff2int(buff) { + let res = BigInteger.zero; + for (let i=0; i=0)) { + let c = Number(r.and(BigInteger("255"))); + buff[o] = c; + o--; + r = r.shiftRight(8); + } + if (!r.eq(BigInteger.zero)) { + throw new Error("Number does not fit in this length"); + } + return buff; +} + + +function utils_bigint_leBuff2int (buff) { + let res = BigInteger.zero; + for (let i=0; i>=1; + } + return res; +} + +utils.bitReverse = function bitReverse(idx, bits) { + return ( + utils_revTable[idx >>> 24] | + (utils_revTable[(idx >>> 16) & 0xFF] << 8) | + (utils_revTable[(idx >>> 8) & 0xFF] << 16) | + (utils_revTable[idx & 0xFF] << 24) + ) >>> (32-bits); +}; + + +utils.log2 = function log2( V ) +{ + return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) ); +}; + +utils.buffReverseBits = function buffReverseBits(buff, eSize) { + const n = buff.byteLength /eSize; + const bits = utils.log2(n); + if (n != (1 << bits)) { + throw new Error("Invalid number of pointers"); + } + for (let i=0; ir) { + const tmp = buff.slice(i*eSize, (i+1)*eSize); + buff.set( buff.slice(r*eSize, (r+1)*eSize), i*eSize); + buff.set(tmp, r*eSize); + } + } +}; + + +utils.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i0) { + // bytes to copy from this page + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset+o, l); + if (l == len) return srcView.slice(); + if (!buff) { + if (len <= PAGE_SIZE) { + buff = new Uint8Array(len); + } else { + buff = new BigBuffer(len); + } + } + buff.set(srcView, len-r); + r = r-l; + p ++; + o = 0; + } + + return buff; + } + + set(buff, offset) { + if (offset === undefined) offset = 0; + + const len = buff.byteLength; + + if (len==0) return; + + const firstPage = Math.floor(offset / PAGE_SIZE); + const lastPage = Math.floor((offset+len-1) / PAGE_SIZE); + + if (firstPage == lastPage) { + if ((buff instanceof BigBuffer)&&(buff.buffers.length==1)) { + return this.buffers[firstPage].set(buff.buffers[0], offset % PAGE_SIZE); + } else { + return this.buffers[firstPage].set(buff, offset % PAGE_SIZE); + } + + } + + + let p = firstPage; + let o = offset % PAGE_SIZE; + let r = len; + while (r>0) { + const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; + const srcView = buff.slice( len -r, len -r+l); + const dstView = new Uint8Array(this.buffers[p].buffer, this.buffers[p].byteOffset + o, l); + dstView.set(srcView); + r = r-l; + p ++; + o = 0; + } + + } +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine_batchconvert.js + + +function buildBatchConvert(tm, fnName, sIn, sOut) { + return async function batchConvert(buffIn) { + const nPoints = Math.floor(buffIn.byteLength / sIn); + if ( nPoints * sIn !== buffIn.byteLength) { + throw new Error("Invalid buffer size"); + } + const pointsPerChunk = Math.floor(nPoints/tm.concurrency); + const opPromises = []; + for (let i=0; i=0; i--) { + this.w[i] = this.square(this.w[i+1]); + } + + if (!this.eq(this.w[0], this.one)) { + throw new Error("Error calculating roots of unity"); + } + + this.batchToMontgomery = buildBatchConvert(tm, prefix + "_batchToMontgomery", this.n8, this.n8); + this.batchFromMontgomery = buildBatchConvert(tm, prefix + "_batchFromMontgomery", this.n8, this.n8); + } + + + op2(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op2Bool(opName, a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp2); + } + + op1(opName, a) { + this.tm.setBuff(this.pOp1, a); + this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + op1Bool(opName, a) { + this.tm.setBuff(this.pOp1, a); + return !!this.tm.instance.exports[this.prefix + opName](this.pOp1, this.pOp3); + } + + add(a,b) { + return this.op2("_add", a, b); + } + + + eq(a,b) { + return this.op2Bool("_eq", a, b); + } + + isZero(a) { + return this.op1Bool("_isZero", a); + } + + sub(a,b) { + return this.op2("_sub", a, b); + } + + neg(a) { + return this.op1("_neg", a); + } + + inv(a) { + return this.op1("_inverse", a); + } + + toMontgomery(a) { + return this.op1("_toMontgomery", a); + } + + fromMontgomery(a) { + return this.op1("_fromMontgomery", a); + } + + mul(a,b) { + return this.op2("_mul", a, b); + } + + div(a, b) { + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_inverse"](this.pOp2, this.pOp2); + this.tm.instance.exports[this.prefix + "_mul"](this.pOp1, this.pOp2, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + square(a) { + return this.op1("_square", a); + } + + isSquare(a) { + return this.op1Bool("_isSquare", a); + } + + sqrt(a) { + return this.op1("_sqrt", a); + } + + exp(a, b) { + if (!(b instanceof Uint8Array)) { + b = toLEBuff(scalar_e(b)); + } + this.tm.setBuff(this.pOp1, a); + this.tm.setBuff(this.pOp2, b); + this.tm.instance.exports[this.prefix + "_exp"](this.pOp1, this.pOp2, b.byteLength, this.pOp3); + return this.tm.getBuff(this.pOp3, this.n8); + } + + isNegative(a) { + return this.op1Bool("_isNegative", a); + } + + e(a, b) { + if (a instanceof Uint8Array) return a; + let ra = scalar_e(a, b); + if (scalar_isNegative(ra)) { + ra = scalar_neg(ra); + if (scalar_gt(ra, this.p)) { + ra = scalar_mod(ra, this.p); + } + ra = scalar_sub(this.p, ra); + } else { + if (scalar_gt(ra, this.p)) { + ra = scalar_mod(ra, this.p); + } + } + const buff = utils_leInt2Buff(ra, this.n8); + return this.toMontgomery(buff); + } + + toString(a, radix) { + const an = this.fromMontgomery(a); + const s = fromRprLE(an, 0); + return scalar_toString(s, radix); + } + + fromRng(rng) { + let v; + const buff = new Uint8Array(this.n8); + do { + v = zero; + for (let i=0; i memory.buffer.byteLength) { + const currentPages = memory.buffer.byteLength / 0x10000; + let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1; + if (requiredPages>MAXMEM) requiredPages=MAXMEM; + memory.grow(requiredPages-currentPages); + } + return res; + } + + function allocBuffer(buffer) { + const p = alloc(buffer.byteLength); + setBuffer(p, buffer); + return p; + } + + function getBuffer(pointer, length) { + const u8 = new Uint8Array(memory.buffer); + return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length); + } + + function setBuffer(pointer, buffer) { + const u8 = new Uint8Array(memory.buffer); + u8.set(new Uint8Array(buffer), pointer); + } + + function runTask(task) { + if (task[0].cmd == "INIT") { + return init(task[0]); + } + const ctx = { + vars: [], + out: [] + }; + const u32a = new Uint32Array(memory.buffer, 0, 1); + const oldAlloc = u32a[0]; + for (let i=0; i. +*/ + +// const MEM_SIZE = 1000; // Memory size in 64K Pakes (512Mb) +const MEM_SIZE = 25; // Memory size in 64K Pakes (1600Kb) + + + + + + +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject)=> { + this.reject = reject; + this.resolve = resolve; + }); + } +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function stringToBase64(str) { + if (threadman_process.browser) { + return globalThis.btoa(str); + } else { + return Buffer.from(str).toString("base64"); + } +} + +const threadSource = stringToBase64("(" + thread.toString() + ")(self)"); +const workerSource = "data:application/javascript;base64," + threadSource; + + + +async function buildThreadManager(wasm, singleThread) { + const tm = new ThreadManager(); + + tm.memory = new WebAssembly.Memory({initial:MEM_SIZE}); + tm.u8 = new Uint8Array(tm.memory.buffer); + tm.u32 = new Uint32Array(tm.memory.buffer); + + const wasmModule = await WebAssembly.compile(wasm.code); + + tm.instance = await WebAssembly.instantiate(wasmModule, { + env: { + "memory": tm.memory + } + }); + + tm.singleThread = singleThread; + tm.initalPFree = tm.u32[0]; // Save the Pointer to free space. + tm.pq = wasm.pq; + tm.pr = wasm.pr; + tm.pG1gen = wasm.pG1gen; + tm.pG1zero = wasm.pG1zero; + tm.pG2gen = wasm.pG2gen; + tm.pG2zero = wasm.pG2zero; + tm.pOneT = wasm.pOneT; + + // tm.pTmp0 = tm.alloc(curve.G2.F.n8*3); + // tm.pTmp1 = tm.alloc(curve.G2.F.n8*3); + + + if (singleThread) { + tm.code = wasm.code; + tm.taskManager = thread(); + await tm.taskManager([{ + cmd: "INIT", + init: MEM_SIZE, + code: tm.code.slice() + }]); + tm.concurrency = 1; + } else { + tm.workers = []; + tm.pendingDeferreds = []; + tm.working = []; + + let concurrency; + + if ((typeof(navigator) === "object") && navigator.hardwareConcurrency) { + concurrency = navigator.hardwareConcurrency; + } else { + concurrency = browser.cpus().length; + } + + if(concurrency == 0){ + concurrency = 2; + } + + // Limit to 64 threads for memory reasons. + if (concurrency>64) concurrency=64; + tm.concurrency = concurrency; + + for (let i = 0; i 0); i++) { + if (this.working[i] == false) { + const work = this.actionQueue.shift(); + this.postAction(i, work.data, work.transfers, work.deferred); + } + } + } + + queueAction(actionData, transfers) { + const d = new Deferred(); + + if (this.singleThread) { + const res = this.taskManager(actionData); + d.resolve(res); + } else { + this.actionQueue.push({ + data: actionData, + transfers: transfers, + deferred: d + }); + this.processWorks(); + } + return d.promise; + } + + resetMemory() { + this.u32[0] = this.initalPFree; + } + + allocBuff(buff) { + const pointer = this.alloc(buff.byteLength); + this.setBuff(pointer, buff); + return pointer; + } + + getBuff(pointer, length) { + return this.u8.slice(pointer, pointer+ length); + } + + setBuff(pointer, buffer) { + this.u8.set(new Uint8Array(buffer), pointer); + } + + alloc(length) { + while (this.u32[0] & 3) this.u32[0]++; // Return always aligned pointers + const res = this.u32[0]; + this.u32[0] += length; + return res; + } + + async terminate() { + for (let i=0; i=0; i--) { + if (!G.isZero(res)) { + for (let j=0; jMAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + if (chunkSize { + if (logger) logger.debug(`Multiexp end: ${logText}: ${i}/${nPoints}`); + return r; + })); + } + + const result = await Promise.all(opPromises); + + let res = G.zero; + for (let i=result.length-1; i>=0; i--) { + res = G.add(res, result[i]); + } + + return res; + } + + G.multiExp = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "jacobian", logger, logText); + }; + G.multiExpAffine = async function multiExpAffine(buffBases, buffScalars, logger, logText) { + return await _multiExp(buffBases, buffScalars, "affine", logger, logText); + }; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine_fft.js + + + + +function buildFFT(curve, groupName) { + const G = curve[groupName]; + const Fr = curve.Fr; + const tm = G.tm; + async function _fft(buff, inverse, inType, outType, logger, loggerTxt) { + + inType = inType || "affine"; + outType = outType || "affine"; + const MAX_BITS_THREAD = 14; + + let sIn, sMid, sOut, fnIn2Mid, fnMid2Out, fnFFTMix, fnFFTJoin, fnFFTFinal; + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g1m_fftFinal"; + } + fnFFTJoin = "g1m_fftJoin"; + fnFFTMix = "g1m_fftMix"; + + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g1m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + if (inverse) { + fnFFTFinal = "g2m_fftFinal"; + } + fnFFTJoin = "g2m_fftJoin"; + fnFFTMix = "g2m_fftMix"; + if (outType == "affine") { + sOut = G.F.n8*2; + fnMid2Out = "g2m_batchToAffine"; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = G.n8; + sMid = G.n8; + sOut = G.n8; + if (inverse) { + fnFFTFinal = "frm_fftFinal"; + } + fnFFTMix = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } + + + let returnArray = false; + if (Array.isArray(buff)) { + buff = array2buffer(buff, sIn); + returnArray = true; + } else { + buff = buff.slice(0, buff.byteLength); + } + + const nPoints = buff.byteLength / sIn; + const bits = utils_log2(nPoints); + + if ((1 << bits) != nPoints) { + throw new Error("fft must be multiple of 2" ); + } + + if (bits == Fr.s +1) { + let buffOut; + + if (inverse) { + buffOut = await _fftExtInv(buff, inType, outType, logger, loggerTxt); + } else { + buffOut = await _fftExt(buff, inType, outType, logger, loggerTxt); + } + + if (returnArray) { + return buffer2array(buffOut, sOut); + } else { + return buffOut; + } + } + + let inv; + if (inverse) { + inv = Fr.inv(Fr.e(nPoints)); + } + + let buffOut; + + buffReverseBits(buff, sIn); + + let chunks; + let pointsInChunk = Math.min(1 << MAX_BITS_THREAD, nPoints); + let nChunks = nPoints / pointsInChunk; + + while ((nChunks < tm.concurrency)&&(pointsInChunk>=16)) { + nChunks *= 2; + pointsInChunk /= 2; + } + + const l2Chunk = utils_log2(pointsInChunk); + + const promises = []; + for (let i = 0; i< nChunks; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix start: ${i}/${nChunks}`); + const task = []; + task.push({cmd: "ALLOC", var: 0, len: sMid*pointsInChunk}); + const buffChunk = buff.slice( (pointsInChunk * i)*sIn, (pointsInChunk * (i+1))*sIn); + task.push({cmd: "SET", var: 0, buff: buffChunk}); + if (fnIn2Mid) { + task.push({cmd: "CALL", fnName:fnIn2Mid, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + for (let j=1; j<=l2Chunk;j++) { + task.push({cmd: "CALL", fnName:fnFFTMix, params: [{var:0}, {val: pointsInChunk}, {val: j}]}); + } + + if (l2Chunk==bits) { + if (fnFFTFinal) { + task.push({cmd: "ALLOCSET", var: 1, buff: inv}); + task.push({cmd: "CALL", fnName: fnFFTFinal, params:[ + {var: 0}, + {val: pointsInChunk}, + {var: 1}, + ]}); + } + if (fnMid2Out) { + task.push({cmd: "CALL", fnName:fnMid2Out, params: [{var:0}, {val: pointsInChunk}, {var: 0}]}); + } + task.push({cmd: "GET", out: 0, var: 0, len: pointsInChunk*sOut}); + } else { + task.push({cmd: "GET", out:0, var: 0, len: sMid*pointsInChunk}); + } + promises.push(tm.queueAction(task).then( (r) => { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} mix end: ${i}/${nChunks}`); + return r; + })); + } + + chunks = await Promise.all(promises); + for (let i = 0; i< nChunks; i++) chunks[i] = chunks[i][0]; + + for (let i = l2Chunk+1; i<=bits; i++) { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join: ${i}/${bits}`); + const nGroups = 1 << (bits - i); + const nChunksPerGroup = nChunks / nGroups; + const opPromises = []; + for (let j=0; j { + if (logger) logger.debug(`${loggerTxt}: fft ${bits} join ${i}/${bits} ${j+1}/${nGroups} ${k}/${nChunksPerGroup/2}`); + return r; + })); + } + } + + const res = await Promise.all(opPromises); + for (let j=0; j0; i--) { + buffOut.set(chunks[i], p); + p += pointsInChunk*sOut; + delete chunks[i]; // Liberate mem + } + buffOut.set(chunks[0].slice(0, (pointsInChunk-1)*sOut), p); + delete chunks[0]; + } else { + for (let i=0; i (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + async function _fftExtInv(buff, inType, outType, logger, loggerTxt) { + let b1, b2; + b1 = buff.slice( 0 , buff.byteLength/2); + b2 = buff.slice( buff.byteLength/2, buff.byteLength); + + const promises = []; + + promises.push( _fft(b1, true, inType, "jacobian", logger, loggerTxt)); + promises.push( _fft(b2, true, inType, "jacobian", logger, loggerTxt)); + + [b1, b2] = await Promise.all(promises); + + const res1 = await _fftJoinExt(b1, b2, "fftJoinExtInv", Fr.one, Fr.shiftInv, "jacobian", outType, logger, loggerTxt); + + let buffOut; + if (res1[0].byteLength > (1<<28)) { + buffOut = new BigBuffer(res1[0].byteLength*2); + } else { + buffOut = new Uint8Array(res1[0].byteLength*2); + } + + buffOut.set(res1[0]); + buffOut.set(res1[1], res1[0].byteLength); + + return buffOut; + } + + + async function _fftJoinExt(buff1, buff2, fn, first, inc, inType, outType, logger, loggerTxt) { + const MAX_CHUNK_SIZE = 1<<16; + const MIN_CHUNK_SIZE = 1<<4; + + let fnName; + let fnIn2Mid, fnMid2Out; + let sOut, sIn, sMid; + + if (groupName == "G1") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g1m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + sMid = G.F.n8*3; + fnName = "g1m_"+fn; + if (outType == "affine") { + fnMid2Out = "g1m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "G2") { + if (inType == "affine") { + sIn = G.F.n8*2; + fnIn2Mid = "g2m_batchToJacobian"; + } else { + sIn = G.F.n8*3; + } + fnName = "g2m_"+fn; + sMid = G.F.n8*3; + if (outType == "affine") { + fnMid2Out = "g2m_batchToAffine"; + sOut = G.F.n8*2; + } else { + sOut = G.F.n8*3; + } + } else if (groupName == "Fr") { + sIn = Fr.n8; + sOut = Fr.n8; + sMid = Fr.n8; + fnName = "frm_" + fn; + } else { + throw new Error("Invalid group"); + } + + if (buff1.byteLength != buff2.byteLength) { + throw new Error("Invalid buffer size"); + } + const nPoints = Math.floor(buff1.byteLength / sIn); + if (nPoints != 1 << utils_log2(nPoints)) { + throw new Error("Invalid number of points"); + } + + let chunkSize = Math.floor(nPoints /tm.concurrency); + if (chunkSize < MIN_CHUNK_SIZE) chunkSize = MIN_CHUNK_SIZE; + if (chunkSize > MAX_CHUNK_SIZE) chunkSize = MAX_CHUNK_SIZE; + + const opPromises = []; + + for (let i=0; i { + if (logger) logger.debug(`${loggerTxt}: fftJoinExt End: ${i}/${nPoints}`); + return r; + }) + ); + } + + const result = await Promise.all(opPromises); + + let fullBuffOut1; + let fullBuffOut2; + if (nPoints * sOut > 1<<28) { + fullBuffOut1 = new BigBuffer(nPoints*sOut); + fullBuffOut2 = new BigBuffer(nPoints*sOut); + } else { + fullBuffOut1 = new Uint8Array(nPoints*sOut); + fullBuffOut2 = new Uint8Array(nPoints*sOut); + } + + let p =0; + for (let i=0; i Fr.s+1) { + if (logger) logger.error("lagrangeEvaluations input too big"); + throw new Error("lagrangeEvaluations input too big"); + } + + let t0 = buff.slice(0, buff.byteLength/2); + let t1 = buff.slice(buff.byteLength/2, buff.byteLength); + + + const shiftToSmallM = Fr.exp(Fr.shift, nPoints/2); + const sConst = Fr.inv( Fr.sub(Fr.one, shiftToSmallM)); + + [t0, t1] = await _fftJoinExt(t0, t1, "prepareLagrangeEvaluation", sConst, Fr.shiftInv, inType, "jacobian", logger, loggerTxt + " prep"); + + const promises = []; + + promises.push( _fft(t0, true, "jacobian", outType, logger, loggerTxt + " t0")); + promises.push( _fft(t1, true, "jacobian", outType, logger, loggerTxt + " t1")); + + [t0, t1] = await Promise.all(promises); + + let buffOut; + if (t0.byteLength > (1<<28)) { + buffOut = new BigBuffer(t0.byteLength*2); + } else { + buffOut = new Uint8Array(t0.byteLength*2); + } + + buffOut.set(t0); + buffOut.set(t1, t0.byteLength); + + return buffOut; + }; + + G.fftMix = async function fftMix(buff) { + const sG = G.F.n8*3; + let fnName, fnFFTJoin; + if (groupName == "G1") { + fnName = "g1m_fftMix"; + fnFFTJoin = "g1m_fftJoin"; + } else if (groupName == "G2") { + fnName = "g2m_fftMix"; + fnFFTJoin = "g2m_fftJoin"; + } else if (groupName == "Fr") { + fnName = "frm_fftMix"; + fnFFTJoin = "frm_fftJoin"; + } else { + throw new Error("Invalid group"); + } + + const nPoints = Math.floor(buff.byteLength / sG); + const power = utils_log2(nPoints); + + let nChunks = 1 << utils_log2(tm.concurrency); + + if (nPoints <= nChunks*2) nChunks = 1; + + const pointsPerChunk = nPoints / nChunks; + + const powerChunk = utils_log2(pointsPerChunk); + + const opPromises = []; + for (let i=0; i=0; i--) { + fullBuffOut.set(result[i][0], p); + p+=result[i][0].byteLength; + } + + return fullBuffOut; + }; +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/src/engine.js + + + + + + + + + + + +async function buildEngine(params) { + + const tm = await buildThreadManager(params.wasm, params.singleThread); + + + const curve = {}; + + curve.q = scalar_e(params.wasm.q); + curve.r = scalar_e(params.wasm.r); + curve.name = params.name; + curve.tm = tm; + curve.prePSize = params.wasm.prePSize; + curve.preQSize = params.wasm.preQSize; + curve.Fr = new WasmField1(tm, "frm", params.n8r, params.r); + curve.F1 = new WasmField1(tm, "f1m", params.n8q, params.q); + curve.F2 = new WasmField2(tm, "f2m", curve.F1); + curve.G1 = new WasmCurve(tm, "g1m", curve.F1, params.wasm.pG1gen, params.wasm.pG1b, params.cofactorG1); + curve.G2 = new WasmCurve(tm, "g2m", curve.F2, params.wasm.pG2gen, params.wasm.pG2b, params.cofactorG2); + curve.F6 = new WasmField3(tm, "f6m", curve.F2); + curve.F12 = new WasmField2(tm, "ftm", curve.F6); + + curve.Gt = curve.F12; + + buildBatchApplyKey(curve, "G1"); + buildBatchApplyKey(curve, "G2"); + buildBatchApplyKey(curve, "Fr"); + + buildMultiexp(curve, "G1"); + buildMultiexp(curve, "G2"); + + buildFFT(curve, "G1"); + buildFFT(curve, "G2"); + buildFFT(curve, "Fr"); + + buildPairing(curve); + + curve.array2buffer = function(arr, sG) { + const buff = new Uint8Array(sG*arr.length); + + for (let i=0; i= 0) { + curve = await bn128_buildBn128(singleThread, plugins); + } else if (["BLS12381"].indexOf(normName) >= 0) { + curve = await bls12381_buildBls12381(singleThread, plugins); + } else { + throw new Error(`Curve not supported: ${name}`); + } + return curve; + + function normalizeName(n) { + return n.toUpperCase().match(/[A-Za-z0-9]+/g).join(""); + } + +} + +;// CONCATENATED MODULE: ./node_modules/ffjavascript/main.js + + +const main_Scalar=scalar_namespaceObject; + + + + + + + + + + + + + + +const main_utils = utils_namespaceObject; + + + + + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/babyjub.js + + +async function babyjub_buildBabyJub() { + const bn128 = await getCurveFromName("bn128", true); + return new BabyJub(bn128.Fr); +} + +class BabyJub { + constructor(F) { + this.F = F; + this.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); + this.pm1d2 = Scalar.div(Scalar.sub(this.p, Scalar.e(1)), Scalar.e(2)); + + this.Generator = [ + F.e("995203441582195749578291179787384436505546430278305826713579947235728471134"), + F.e("5472060717959818805561601436314318772137091100104008585924551046643952123905") + ]; + this.Base8 = [ + F.e("5299619240641551281634865583518297030282874472190772894086521144482721001553"), + F.e("16950150798460657717958625567821834550301663161624707787222815936182638968203") + ]; + this.order = Scalar.fromString("21888242871839275222246405745257275088614511777268538073601725287587578984328"); + this.subOrder = Scalar.shiftRight(this.order, 3); + this.A = F.e("168700"); + this.D = F.e("168696"); + } + + + addPoint(a,b) { + const F = this.F; + + const res = []; + + /* does the equivalent of: + res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) * bigInt(bigInt("1") + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q); + res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt("1") - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q); + */ + + const beta = F.mul(a[0],b[1]); + const gamma = F.mul(a[1],b[0]); + const delta = F.mul( + F.sub(a[1], F.mul(this.A, a[0])), + F.add(b[0], b[1]) + ); + const tau = F.mul(beta, gamma); + const dtau = F.mul(this.D, tau); + + res[0] = F.div( + F.add(beta, gamma), + F.add(F.one, dtau) + ); + + res[1] = F.div( + F.add(delta, F.sub(F.mul(this.A,beta), gamma)), + F.sub(F.one, dtau) + ); + + return res; + } + + mulPointEscalar(base, e) { + const F = this.F; + let res = [F.e("0"),F.e("1")]; + let rem = e; + let exp = base; + + while (! Scalar.isZero(rem)) { + if (Scalar.isOdd(rem)) { + res = this.addPoint(res, exp); + } + exp = this.addPoint(exp, exp); + rem = Scalar.shiftRight(rem, 1); + } + + return res; + } + + inSubgroup(P) { + const F = this.F; + if (!this.inCurve(P)) return false; + const res= this.mulPointEscalar(P, this.subOrder); + return (F.isZero(res[0]) && F.eq(res[1], F.one)); + } + + inCurve(P) { + const F = this.F; + const x2 = F.square(P[0]); + const y2 = F.square(P[1]); + + if (!F.eq( + F.add(F.mul(this.A, x2), y2), + F.add(F.one, F.mul(F.mul(x2, y2), this.D)))) return false; + + return true; + } + + packPoint(P) { + const F = this.F; + const buff = new Uint8Array(32); + F.toRprLE(buff, 0, P[1]); + const n = F.toObject(P[0]); + if (Scalar.gt(n, this.pm1d2)) { + buff[31] = buff[31] | 0x80; + } + return buff; + } + + unpackPoint(buff) { + const F = this.F; + let sign = false; + const P = new Array(2); + if (buff[31] & 0x80) { + sign = true; + buff[31] = buff[31] & 0x7F; + } + P[1] = F.fromRprLE(buff, 0); + if (Scalar.gt(F.toObject(P[1]), this.p)) return null; + + const y2 = F.square(P[1]); + + const x2 = F.div( + F.sub(F.one, y2), + F.sub(this.A, F.mul(this.D, y2)) + ); + + const x2h = F.exp(x2, F.half); + if (! F.eq(F.one, x2h)) return null; + + let x = F.sqrt(x2); + + if (x == null) return null; + + if (sign) x = F.neg(x); + + P[0] = x; + + return P; + } +} + +// EXTERNAL MODULE: ./node_modules/blake2b/index.js +var node_modules_blake2b = __webpack_require__(2206); +// EXTERNAL MODULE: ./node_modules/blake-hash/js.js +var js = __webpack_require__(654); +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/pedersen_hash.js +/* provided dependency */ var pedersen_hash_Buffer = __webpack_require__(8287)["Buffer"]; + + + + + +const GENPOINT_PREFIX = "PedersenGenerator"; +const windowSize = 4; +const nWindowsPerSegment = 50; + +async function pedersen_hash_buildPedersenHash() { + const babyJub = await buildBabyJub(); + return new PedersenHash(babyJub); +} + +class PedersenHash { + + constructor(babyJub) { + this.babyJub = babyJub; + this.bases = []; + } + + baseHash(type, S) { + if (type == "blake") { + return createBlakeHash("blake256").update(S).digest(); + } else if (type == "blake2b") { + return pedersen_hash_Buffer.from(blake2b(32).update(pedersen_hash_Buffer.from(S)).digest()); + } + } + + hash(msg, options) { + options = options || {}; + options.baseHash = options.baseHash || "blake"; + const babyJub = this.babyJub; + const bitsPerSegment = windowSize*nWindowsPerSegment; + const bits = this.buffer2bits(msg); + + const nSegments = Math.floor((bits.length - 1)/(windowSize*nWindowsPerSegment)) +1; + + let accP = [babyJub.F.zero,babyJub.F.one]; + + for (let s=0; s> 1; + res[i*8+2] = (b & 0x04) >> 2; + res[i*8+3] = (b & 0x08) >> 3; + res[i*8+4] = (b & 0x10) >> 4; + res[i*8+5] = (b & 0x20) >> 5; + res[i*8+6] = (b & 0x40) >> 6; + res[i*8+7] = (b & 0x80) >> 7; + } + return res; + } +} + + + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimc7.js + + + + +const SEED = "mimc"; +const NROUNDS = 91; + +async function mimc7_buildMimc7() { + const bn128 = await getCurveFromName("bn128", true); + return new Mimc7(bn128.Fr); +} + + +class Mimc7 { + constructor (F) { + this.F = F; + this.cts = this.getConstants(SEED, 91); + } + + getIV(seed) { + const F = this.F; + if (typeof seed === "undefined") seed = SEED; + const c = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(seed+"_iv")); + const cn = Scalar.e(c); + const iv = Scalar.mod(cn, F.p); + return iv; + }; + + getConstants(seed, nRounds) { + const F = this.F; + if (typeof seed === "undefined") seed = SEED; + if (typeof nRounds === "undefined") nRounds = NROUNDS; + const cts = new Array(nRounds); + let c = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(SEED)); + for (let i=1; i { + let buff; + let n; + if (Array.isArray(arr)) { + n = arr.length; + buff = new Uint8Array(n*32); + for (let i=0; i16)) throw new Error("Invalid poseidon size"); + + if (typeof state == "undefined") { + state = F.zero; + } else { + state = F.e(state); + } + bn128.tm.setBuff(pState, state); + nOut = nOut || 1; + + bn128.tm.instance.exports.poseidon(pState, pIn, n, pOut, nOut); + if (nOut == 1) { + return bn128.tm.getBuff(pOut, 32); + } else { + const out = []; + for (let i=0; i { + try { + if ("test".normalize(form) !== "test") { + throw new Error("bad normalize"); + } + ; + } + catch (error) { + missing.push(form); + } + }); + if (missing.length) { + throw new Error("missing " + missing.join(", ")); + } + if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) { + throw new Error("broken implementation"); + } + } + catch (error) { + return error.message; + } + return null; +} +const _normalizeError = _checkNormalize(); +var LogLevel; +(function (LogLevel) { + LogLevel["DEBUG"] = "DEBUG"; + LogLevel["INFO"] = "INFO"; + LogLevel["WARNING"] = "WARNING"; + LogLevel["ERROR"] = "ERROR"; + LogLevel["OFF"] = "OFF"; +})(LogLevel || (LogLevel = {})); +var ErrorCode; +(function (ErrorCode) { + /////////////////// + // Generic Errors + // Unknown Error + ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; + // Not Implemented + ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; + // Unsupported Operation + // - operation + ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; + // Network Error (i.e. Ethereum Network, such as an invalid chain ID) + // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown) + ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR"; + // Some sort of bad response from the server + ErrorCode["SERVER_ERROR"] = "SERVER_ERROR"; + // Timeout + ErrorCode["TIMEOUT"] = "TIMEOUT"; + /////////////////// + // Operational Errors + // Buffer Overrun + ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; + // Numeric Fault + // - operation: the operation being executed + // - fault: the reason this faulted + ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT"; + /////////////////// + // Argument Errors + // Missing new operator to an object + // - name: The name of the class + ErrorCode["MISSING_NEW"] = "MISSING_NEW"; + // Invalid argument (e.g. value is incompatible with type) to a function: + // - argument: The argument name that was invalid + // - value: The value of the argument + ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; + // Missing argument to a function: + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; + // Too many arguments + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; + /////////////////// + // Blockchain Errors + // Call exception + // - transaction: the transaction + // - address?: the contract address + // - args?: The arguments passed into the function + // - method?: The Solidity method signature + // - errorSignature?: The EIP848 error signature + // - errorArgs?: The EIP848 error parameters + // - reason: The reason (only for EIP848 "Error(string)") + ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION"; + // Insufficient funds (< value + gasLimit * gasPrice) + // - transaction: the transaction attempted + ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; + // Nonce has already been used + // - transaction: the transaction attempted + ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED"; + // The replacement fee for the transaction is too low + // - transaction: the transaction attempted + ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; + // The gas limit could not be estimated + // - transaction: the transaction passed to estimateGas + ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; + // The transaction was replaced by one with a higher gas price + // - reason: "cancelled", "replaced" or "repriced" + // - cancelled: true if reason == "cancelled" or reason == "replaced") + // - hash: original transaction hash + // - replacement: the full TransactionsResponse for the replacement + // - receipt: the receipt of the replacement + ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; + /////////////////// + // Interaction Errors + // The user rejected the action, such as signing a message or sending + // a transaction + ErrorCode["ACTION_REJECTED"] = "ACTION_REJECTED"; +})(ErrorCode || (ErrorCode = {})); +; +const HEX = "0123456789abcdef"; +class Logger { + constructor(version) { + Object.defineProperty(this, "version", { + enumerable: true, + value: version, + writable: false + }); + } + _log(logLevel, args) { + const level = logLevel.toLowerCase(); + if (LogLevels[level] == null) { + this.throwArgumentError("invalid log level name", "logLevel", logLevel); + } + if (_logLevel > LogLevels[level]) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this._log(Logger.levels.DEBUG, args); + } + info(...args) { + this._log(Logger.levels.INFO, args); + } + warn(...args) { + this._log(Logger.levels.WARNING, args); + } + makeError(message, code, params) { + // Errors are being censored + if (_censorErrors) { + return this.makeError("censored error", code, {}); + } + if (!code) { + code = Logger.errors.UNKNOWN_ERROR; + } + if (!params) { + params = {}; + } + const messageDetails = []; + Object.keys(params).forEach((key) => { + const value = params[key]; + try { + if (value instanceof Uint8Array) { + let hex = ""; + for (let i = 0; i < value.length; i++) { + hex += HEX[value[i] >> 4]; + hex += HEX[value[i] & 0x0f]; + } + messageDetails.push(key + "=Uint8Array(0x" + hex + ")"); + } + else { + messageDetails.push(key + "=" + JSON.stringify(value)); + } + } + catch (error) { + messageDetails.push(key + "=" + JSON.stringify(params[key].toString())); + } + }); + messageDetails.push(`code=${code}`); + messageDetails.push(`version=${this.version}`); + const reason = message; + let url = ""; + switch (code) { + case ErrorCode.NUMERIC_FAULT: { + url = "NUMERIC_FAULT"; + const fault = message; + switch (fault) { + case "overflow": + case "underflow": + case "division-by-zero": + url += "-" + fault; + break; + case "negative-power": + case "negative-width": + url += "-unsupported"; + break; + case "unbound-bitwise-result": + url += "-unbound-result"; + break; + } + break; + } + case ErrorCode.CALL_EXCEPTION: + case ErrorCode.INSUFFICIENT_FUNDS: + case ErrorCode.MISSING_NEW: + case ErrorCode.NONCE_EXPIRED: + case ErrorCode.REPLACEMENT_UNDERPRICED: + case ErrorCode.TRANSACTION_REPLACED: + case ErrorCode.UNPREDICTABLE_GAS_LIMIT: + url = code; + break; + } + if (url) { + message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]"; + } + if (messageDetails.length) { + message += " (" + messageDetails.join(", ") + ")"; + } + // @TODO: Any?? + const error = new Error(message); + error.reason = reason; + error.code = code; + Object.keys(params).forEach(function (key) { + error[key] = params[key]; + }); + return error; + } + throwError(message, code, params) { + throw this.makeError(message, code, params); + } + throwArgumentError(message, name, value) { + return this.throwError(message, Logger.errors.INVALID_ARGUMENT, { + argument: name, + value: value + }); + } + assert(condition, message, code, params) { + if (!!condition) { + return; + } + this.throwError(message, code, params); + } + assertArgument(condition, message, name, value) { + if (!!condition) { + return; + } + this.throwArgumentError(message, name, value); + } + checkNormalize(message) { + if (message == null) { + message = "platform missing String.prototype.normalize"; + } + if (_normalizeError) { + this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "String.prototype.normalize", form: _normalizeError + }); + } + } + checkSafeUint53(value, message) { + if (typeof (value) !== "number") { + return; + } + if (message == null) { + message = "value not safe"; + } + if (value < 0 || value >= 0x1fffffffffffff) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "out-of-safe-range", + value: value + }); + } + if (value % 1) { + this.throwError(message, Logger.errors.NUMERIC_FAULT, { + operation: "checkSafeInteger", + fault: "non-integer", + value: value + }); + } + } + checkArgumentCount(count, expectedCount, message) { + if (message) { + message = ": " + message; + } + else { + message = ""; + } + if (count < expectedCount) { + this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, { + count: count, + expectedCount: expectedCount + }); + } + } + checkNew(target, kind) { + if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + checkAbstract(target, kind) { + if (target === kind) { + this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" }); + } + else if (target === Object || target == null) { + this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name }); + } + } + static globalLogger() { + if (!_globalLogger) { + _globalLogger = new Logger(version); + } + return _globalLogger; + } + static setCensorship(censorship, permanent) { + if (!censorship && permanent) { + this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + if (_permanentCensorErrors) { + if (!censorship) { + return; + } + this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setCensorship" + }); + } + _censorErrors = !!censorship; + _permanentCensorErrors = !!permanent; + } + static setLogLevel(logLevel) { + const level = LogLevels[logLevel.toLowerCase()]; + if (level == null) { + Logger.globalLogger().warn("invalid log level - " + logLevel); + return; + } + _logLevel = level; + } + static from(version) { + return new Logger(version); + } +} +Logger.errors = ErrorCode; +Logger.levels = LogLevel; +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/_version.js +const _version_version = "bytes/5.7.0"; +//# sourceMappingURL=_version.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/index.js + + + +const logger = new Logger(_version_version); +/////////////////////////////// +function isHexable(value) { + return !!(value.toHexString); +} +function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function () { + const args = Array.prototype.slice.call(arguments); + return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); + }; + return array; +} +function isBytesLike(value) { + return ((isHexString(value) && !(value.length % 2)) || isBytes(value)); +} +function isInteger(value) { + return (typeof (value) === "number" && value == value && (value % 1) === 0); +} +function isBytes(value) { + if (value == null) { + return false; + } + if (value.constructor === Uint8Array) { + return true; + } + if (typeof (value) === "string") { + return false; + } + if (!isInteger(value.length) || value.length < 0) { + return false; + } + for (let i = 0; i < value.length; i++) { + const v = value[i]; + if (!isInteger(v) || v < 0 || v >= 256) { + return false; + } + } + return true; +} +function lib_esm_arrayify(value, options) { + if (!options) { + options = {}; + } + if (typeof (value) === "number") { + logger.checkSafeUint53(value, "invalid arrayify value"); + const result = []; + while (value) { + result.unshift(value & 0xff); + value = parseInt(String(value / 256)); + } + if (result.length === 0) { + result.push(0); + } + return addSlice(new Uint8Array(result)); + } + if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + value = value.toHexString(); + } + if (isHexString(value)) { + let hex = value.substring(2); + if (hex.length % 2) { + if (options.hexPad === "left") { + hex = "0" + hex; + } + else if (options.hexPad === "right") { + hex += "0"; + } + else { + logger.throwArgumentError("hex data is odd-length", "value", value); + } + } + const result = []; + for (let i = 0; i < hex.length; i += 2) { + result.push(parseInt(hex.substring(i, i + 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + if (isBytes(value)) { + return addSlice(new Uint8Array(value)); + } + return logger.throwArgumentError("invalid arrayify value", "value", value); +} +function concat(items) { + const objects = items.map(item => lib_esm_arrayify(item)); + const length = objects.reduce((accum, item) => (accum + item.length), 0); + const result = new Uint8Array(length); + objects.reduce((offset, object) => { + result.set(object, offset); + return offset + object.length; + }, 0); + return addSlice(result); +} +function stripZeros(value) { + let result = lib_esm_arrayify(value); + if (result.length === 0) { + return result; + } + // Find the first non-zero entry + let start = 0; + while (start < result.length && result[start] === 0) { + start++; + } + // If we started with zeros, strip them + if (start) { + result = result.slice(start); + } + return result; +} +function zeroPad(value, length) { + value = lib_esm_arrayify(value); + if (value.length > length) { + logger.throwArgumentError("value out of range", "value", arguments[0]); + } + const result = new Uint8Array(length); + result.set(value, length - value.length); + return addSlice(result); +} +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (length && value.length !== 2 + 2 * length) { + return false; + } + return true; +} +const HexCharacters = "0123456789abcdef"; +function hexlify(value, options) { + if (!options) { + options = {}; + } + if (typeof (value) === "number") { + logger.checkSafeUint53(value, "invalid hexlify value"); + let hex = ""; + while (value) { + hex = HexCharacters[value & 0xf] + hex; + value = Math.floor(value / 16); + } + if (hex.length) { + if (hex.length % 2) { + hex = "0" + hex; + } + return "0x" + hex; + } + return "0x00"; + } + if (typeof (value) === "bigint") { + value = value.toString(16); + if (value.length % 2) { + return ("0x0" + value); + } + return "0x" + value; + } + if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + return value.toHexString(); + } + if (isHexString(value)) { + if (value.length % 2) { + if (options.hexPad === "left") { + value = "0x0" + value.substring(2); + } + else if (options.hexPad === "right") { + value += "0"; + } + else { + logger.throwArgumentError("hex data is odd-length", "value", value); + } + } + return value.toLowerCase(); + } + if (isBytes(value)) { + let result = "0x"; + for (let i = 0; i < value.length; i++) { + let v = value[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; + } + return logger.throwArgumentError("invalid hexlify value", "value", value); +} +/* +function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number { + if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") { + return "0x0" + value.substring(2); + } + return value; +} +*/ +function hexDataLength(data) { + if (typeof (data) !== "string") { + data = hexlify(data); + } + else if (!isHexString(data) || (data.length % 2)) { + return null; + } + return (data.length - 2) / 2; +} +function hexDataSlice(data, offset, endOffset) { + if (typeof (data) !== "string") { + data = hexlify(data); + } + else if (!isHexString(data) || (data.length % 2)) { + logger.throwArgumentError("invalid hexData", "value", data); + } + offset = 2 + 2 * offset; + if (endOffset != null) { + return "0x" + data.substring(offset, 2 + 2 * endOffset); + } + return "0x" + data.substring(offset); +} +function hexConcat(items) { + let result = "0x"; + items.forEach((item) => { + result += hexlify(item).substring(2); + }); + return result; +} +function hexValue(value) { + const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" })); + if (trimmed === "0x") { + return "0x0"; + } + return trimmed; +} +function hexStripZeros(value) { + if (typeof (value) !== "string") { + value = hexlify(value); + } + if (!isHexString(value)) { + logger.throwArgumentError("invalid hex string", "value", value); + } + value = value.substring(2); + let offset = 0; + while (offset < value.length && value[offset] === "0") { + offset++; + } + return "0x" + value.substring(offset); +} +function hexZeroPad(value, length) { + if (typeof (value) !== "string") { + value = hexlify(value); + } + else if (!isHexString(value)) { + logger.throwArgumentError("invalid hex string", "value", value); + } + if (value.length > 2 * length + 2) { + logger.throwArgumentError("value out of range", "value", arguments[1]); + } + while (value.length < 2 * length + 2) { + value = "0x0" + value.substring(2); + } + return value; +} +function splitSignature(signature) { + const result = { + r: "0x", + s: "0x", + _vs: "0x", + recoveryParam: 0, + v: 0, + yParityAndS: "0x", + compact: "0x" + }; + if (isBytesLike(signature)) { + let bytes = lib_esm_arrayify(signature); + // Get the r, s and v + if (bytes.length === 64) { + // EIP-2098; pull the v from the top bit of s and clear it + result.v = 27 + (bytes[32] >> 7); + bytes[32] &= 0x7f; + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + } + else if (bytes.length === 65) { + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + result.v = bytes[64]; + } + else { + logger.throwArgumentError("invalid signature string", "signature", signature); + } + // Allow a recid to be used as the v + if (result.v < 27) { + if (result.v === 0 || result.v === 1) { + result.v += 27; + } + else { + logger.throwArgumentError("signature invalid v byte", "signature", signature); + } + } + // Compute recoveryParam from v + result.recoveryParam = 1 - (result.v % 2); + // Compute _vs from recoveryParam and s + if (result.recoveryParam) { + bytes[32] |= 0x80; + } + result._vs = hexlify(bytes.slice(32, 64)); + } + else { + result.r = signature.r; + result.s = signature.s; + result.v = signature.v; + result.recoveryParam = signature.recoveryParam; + result._vs = signature._vs; + // If the _vs is available, use it to populate missing s, v and recoveryParam + // and verify non-missing s, v and recoveryParam + if (result._vs != null) { + const vs = zeroPad(lib_esm_arrayify(result._vs), 32); + result._vs = hexlify(vs); + // Set or check the recid + const recoveryParam = ((vs[0] >= 128) ? 1 : 0); + if (result.recoveryParam == null) { + result.recoveryParam = recoveryParam; + } + else if (result.recoveryParam !== recoveryParam) { + logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature); + } + // Set or check the s + vs[0] &= 0x7f; + const s = hexlify(vs); + if (result.s == null) { + result.s = s; + } + else if (result.s !== s) { + logger.throwArgumentError("signature v mismatch _vs", "signature", signature); + } + } + // Use recid and v to populate each other + if (result.recoveryParam == null) { + if (result.v == null) { + logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature); + } + else if (result.v === 0 || result.v === 1) { + result.recoveryParam = result.v; + } + else { + result.recoveryParam = 1 - (result.v % 2); + } + } + else { + if (result.v == null) { + result.v = 27 + result.recoveryParam; + } + else { + const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2)); + if (result.recoveryParam !== recId) { + logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature); + } + } + } + if (result.r == null || !isHexString(result.r)) { + logger.throwArgumentError("signature missing or invalid r", "signature", signature); + } + else { + result.r = hexZeroPad(result.r, 32); + } + if (result.s == null || !isHexString(result.s)) { + logger.throwArgumentError("signature missing or invalid s", "signature", signature); + } + else { + result.s = hexZeroPad(result.s, 32); + } + const vs = lib_esm_arrayify(result.s); + if (vs[0] >= 128) { + logger.throwArgumentError("signature s out of range", "signature", signature); + } + if (result.recoveryParam) { + vs[0] |= 0x80; + } + const _vs = hexlify(vs); + if (result._vs) { + if (!isHexString(result._vs)) { + logger.throwArgumentError("signature invalid _vs", "signature", signature); + } + result._vs = hexZeroPad(result._vs, 32); + } + // Set or check the _vs + if (result._vs == null) { + result._vs = _vs; + } + else if (result._vs !== _vs) { + logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature); + } + } + result.yParityAndS = result._vs; + result.compact = result.r + result.yParityAndS.substring(2); + return result; +} +function joinSignature(signature) { + signature = splitSignature(signature); + return hexlify(concat([ + signature.r, + signature.s, + (signature.recoveryParam ? "0x1c" : "0x1b") + ])); +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/keccak256/lib.esm/index.js + + + +function keccak256(data) { + return '0x' + sha3_default().keccak_256(lib_esm_arrayify(data)); +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/_version.js +const lib_esm_version_version = "strings/5.7.0"; +//# sourceMappingURL=_version.js.map +;// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/utf8.js + + + + +const utf8_logger = new Logger(lib_esm_version_version); +/////////////////////////////// +var UnicodeNormalizationForm; +(function (UnicodeNormalizationForm) { + UnicodeNormalizationForm["current"] = ""; + UnicodeNormalizationForm["NFC"] = "NFC"; + UnicodeNormalizationForm["NFD"] = "NFD"; + UnicodeNormalizationForm["NFKC"] = "NFKC"; + UnicodeNormalizationForm["NFKD"] = "NFKD"; +})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); +; +var Utf8ErrorReason; +(function (Utf8ErrorReason) { + // A continuation byte was present where there was nothing to continue + // - offset = the index the codepoint began in + Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; + // An invalid (non-continuation) byte to start a UTF-8 codepoint was found + // - offset = the index the codepoint began in + Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix"; + // The string is too short to process the expected codepoint + // - offset = the index the codepoint began in + Utf8ErrorReason["OVERRUN"] = "string overrun"; + // A missing continuation byte was expected but not found + // - offset = the index the continuation byte was expected at + Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte"; + // The computed code point is outside the range for UTF-8 + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; outside the UTF-8 range + Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range"; + // UTF-8 strings may not contain UTF-16 surrogate pairs + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range + Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate"; + // The string is an overlong representation + // - offset = start of this codepoint + // - badCodepoint = the computed codepoint; already bounds checked + Utf8ErrorReason["OVERLONG"] = "overlong representation"; +})(Utf8ErrorReason || (Utf8ErrorReason = {})); +; +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return utf8_logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === Utf8ErrorReason.OVERRUN) { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === Utf8ErrorReason.OVERLONG) { + output.push(badCodepoint); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +// Common error handing strategies +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + bytes = arrayify(bytes); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result); + } + else { + i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { + if (form != UnicodeNormalizationForm.current) { + utf8_logger.checkNormalize(); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return lib_esm_arrayify(result); +} +; +function escapeChar(value) { + const hex = ("0000" + value.toString(16)); + return "\\u" + hex.substring(hex.length - 4); +} +function _toEscapedUtf8String(bytes, onError) { + return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => { + if (codePoint < 256) { + switch (codePoint) { + case 8: return "\\b"; + case 9: return "\\t"; + case 10: return "\\n"; + case 13: return "\\r"; + case 34: return "\\\""; + case 92: return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 0xffff) { + return escapeChar(codePoint); + } + codePoint -= 0x10000; + return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); + }).join("") + '"'; +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +//# sourceMappingURL=utf8.js.map +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimcsponge.js + + + +const mimcsponge_SEED = "mimcsponge"; +const mimcsponge_NROUNDS = 220; + +async function mimcsponge_buildMimcSponge() { + const bn128 = await curves_getCurveFromName("bn128", true); + return new MimcSponge(bn128.Fr); +} + +class MimcSponge { + constructor (F) { + this.F = F; + this.cts = this.getConstants(mimcsponge_SEED, mimcsponge_NROUNDS); + } + + getIV (seed) { + const F = this.F; + if (typeof seed === "undefined") seed = mimcsponge_SEED; + const c = keccak256(toUtf8Bytes(seed+"_iv")); + const cn = main_Scalar.e(c); + const iv = cn.mod(F.p); + return iv; + }; + + getConstants (seed, nRounds) { + const F = this.F; + if (typeof seed === "undefined") seed = mimcsponge_SEED; + if (typeof nRounds === "undefined") nRounds = mimcsponge_NROUNDS; + const cts = new Array(nRounds); + let c = keccak256(toUtf8Bytes(mimcsponge_SEED));; + for (let i=1; i= this.babyJub.subOrder) return false; + + const hm = this.mimc7.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + verifyPoseidon(msg, sig, A) { + + // Check parameters + if (typeof sig != "object") return false; + if (!Array.isArray(sig.R8)) return false; + if (sig.R8.length!= 2) return false; + if (!this.babyJub.inCurve(sig.R8)) return false; + if (!Array.isArray(A)) return false; + if (A.length!= 2) return false; + if (!this.babyJub.inCurve(A)) return false; + if (sig.S>= this.babyJub.subOrder) return false; + + const hm = this.poseidon([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + verifyMiMCSponge(msg, sig, A) { + + // Check parameters + if (typeof sig != "object") return false; + if (!Array.isArray(sig.R8)) return false; + if (sig.R8.length!= 2) return false; + if (!this.babyJub.inCurve(sig.R8)) return false; + if (!Array.isArray(A)) return false; + if (A.length!= 2) return false; + if (!this.babyJub.inCurve(A)) return false; + if (sig.S>= this.babyJub.subOrder) return false; + + const hm = this.mimcSponge.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]); + const hms = Scalar.e(this.babyJub.F.toObject(hm)); + + const Pleft = this.babyJub.mulPointEscalar(this.babyJub.Base8, sig.S); + let Pright = this.babyJub.mulPointEscalar(A, Scalar.mul(hms, 8)); + Pright = this.babyJub.addPoint(sig.R8, Pright); + + if (!this.babyJub.F.eq(Pleft[0],Pright[0])) return false; + if (!this.babyJub.F.eq(Pleft[1],Pright[1])) return false; + return true; + } + + packSignature(sig) { + const buff = new Uint8Array(64); + const R8p = this.babyJub.packPoint(sig.R8); + buff.set(R8p, 0) + const Sp = Scalar.toRprLE(buff, 32, sig.S, 32); + return buff; + } + + unpackSignature(sigBuff) { + return { + R8: this.babyJub.unpackPoint(sigBuff.slice(0,32)), + S: Scalar.fromRprLE(sigBuff, 32, 32) + }; + } +} + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/evmasm.js +// Copyright (c) 2018 Jordi Baylina +// License: LGPL-3.0+ +// + + + + +class evmasm_Contract { + constructor() { + this.code = []; + this.labels = {}; + this.pendingLabels = {}; + } + + createTxData() { + let C; + + // Check all labels are defined + const pendingLabels = Object.keys(this.pendingLabels); + if (pendingLabels.length>0) { + throw new Error("Lables not defined: "+ pendingLabels.join(", ")); + } + + let setLoaderLength = 0; + let genLoadedLength = -1; + + while (genLoadedLength!=setLoaderLength) { + setLoaderLength = genLoadedLength; + C = new evmasm_Contract(); + C.codesize(); + C.push(setLoaderLength); + C.push(0); + C.codecopy(); + + C.push(this.code.length); + C.push(0); + C.return(); + genLoadedLength = C.code.length; + } + + return ethers.utils.hexlify(C.code.concat(this.code)); + } + + stop() { this.code.push(0x00); } + add() { this.code.push(0x01); } + mul() { this.code.push(0x02); } + sub() { this.code.push(0x03); } + div() { this.code.push(0x04); } + sdiv() { this.code.push(0x05); } + mod() { this.code.push(0x06); } + smod() { this.code.push(0x07); } + addmod() { this.code.push(0x08); } + mulmod() { this.code.push(0x09); } + exp() { this.code.push(0x0a); } + signextend() { this.code.push(0x0b); } + + lt() { this.code.push(0x10); } + gt() { this.code.push(0x11); } + slt() { this.code.push(0x12); } + sgt() { this.code.push(0x13); } + eq() { this.code.push(0x14); } + iszero() { this.code.push(0x15); } + and() { this.code.push(0x16); } + or() { this.code.push(0x17); } + shor() { this.code.push(0x18); } + not() { this.code.push(0x19); } + byte() { this.code.push(0x1a); } + + keccak() { this.code.push(0x20); } + sha3() { this.code.push(0x20); } // alias + + address() { this.code.push(0x30); } + balance() { this.code.push(0x31); } + origin() { this.code.push(0x32); } + caller() { this.code.push(0x33); } + callvalue() { this.code.push(0x34); } + calldataload() { this.code.push(0x35); } + calldatasize() { this.code.push(0x36); } + calldatacopy() { this.code.push(0x37); } + codesize() { this.code.push(0x38); } + codecopy() { this.code.push(0x39); } + gasprice() { this.code.push(0x3a); } + extcodesize() { this.code.push(0x3b); } + extcodecopy() { this.code.push(0x3c); } + returndatasize() { this.code.push(0x3d); } + returndatacopy() { this.code.push(0x3e); } + + blockhash() { this.code.push(0x40); } + coinbase() { this.code.push(0x41); } + timestamp() { this.code.push(0x42); } + number() { this.code.push(0x43); } + difficulty() { this.code.push(0x44); } + gaslimit() { this.code.push(0x45); } + + pop() { this.code.push(0x50); } + mload() { this.code.push(0x51); } + mstore() { this.code.push(0x52); } + mstore8() { this.code.push(0x53); } + sload() { this.code.push(0x54); } + sstore() { this.code.push(0x55); } + + _pushLabel(label) { + if (typeof this.labels[label] != "undefined") { + this.push(this.labels[label]); + } else { + this.pendingLabels[label] = this.pendingLabels[label] || []; + this.pendingLabels[label].push(this.code.length); + this.push("0x000000"); + } + } + + _fillLabel(label) { + if (!this.pendingLabels[label]) return; + + let dst = this.labels[label]; + + const dst3 = [dst >> 16, (dst >> 8) & 0xFF, dst & 0xFF]; + + this.pendingLabels[label].forEach((p) => { + for (let i=0; i<3; i++) { + this.code[p+i+1] = dst3[i]; + } + }); + + delete this.pendingLabels[label]; + } + + + jmp(label) { + if (typeof label !== "undefined") { + this._pushLabel(label); + } + this.code.push(0x56); + } + + jmpi(label) { + if (typeof label !== "undefined") { + this._pushLabel(label); + } + this.code.push(0x57); + } + + pc() { this.code.push(0x58); } + msize() { this.code.push(0x59); } + gas() { this.code.push(0x5a); } + label(name) { + if (typeof this.labels[name] != "undefined") { + throw new Error("Label already defined"); + } + this.labels[name] = this.code.length; + this.code.push(0x5b); + + this._fillLabel(name); + } + + push(data) { + if ((typeof data !== "string") || (data.slice(0,2) != "0x")) { + let v = Scalar.e(data); + if (Scalar.isNegative(v)) { + v = Scalar.add(Scalar.shl(Scalar.e(1), 256), v); + } + let S = Scalar.toString(v, 16); + if (S.length % 2) S = "0"+S; + S = "0x" +S; + data = S; + } + const d = ethers.utils.arrayify(data); + if (d.length == 0 || d.length > 32) { + throw new Error("Assertion failed"); + } + const a = []; + this.code.push(0x5F + d.length); + for (let i=0; i= 16) { + throw new Error("Assertion failed"); + } + this.code.push(0x80 + n); + } + + swap(n) { + if (n < 1 || n > 16) { + throw new Error("Assertion failed"); + } + this.code.push(0x8f + n); + } + + log0() { this.code.push(0xa0); } + log1() { this.code.push(0xa1); } + log2() { this.code.push(0xa2); } + log3() { this.code.push(0xa3); } + log4() { this.code.push(0xa4); } + + create() { this.code.push(0xf0); } + call() { this.code.push(0xf1); } + callcode() { this.code.push(0xf2); } + return() { this.code.push(0xf3); } + delegatecall() { this.code.push(0xf4); } + + staticcall() { this.code.push(0xfa); } + revert() { this.code.push(0xfd); } + invalid() { this.code.push(0xfe); } + selfdestruct() { this.code.push(0xff); } +} + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/mimc7_gencontract.js +// Copyright (c) 2018 Jordi Baylina +// License: LGPL-3.0+ +// + + + + + +function createCode(seed, n) { + + let ci = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(seed));; + + const C = new Contract(); + + C.push(0x44); + C.push("0x00"); + C.push("0x00"); + C.calldatacopy(); + C.push("0x0100000000000000000000000000000000000000000000000000000000"); + C.push("0x00"); + C.mload(); + C.div(); + C.push("0xd15ca109"); // MiMCpe7(uint256,uint256) +// C.push("0x8c42199e"); // MiMCpe7(uint256,uint256,uint256) + C.eq(); + C.jmpi("start"); + C.invalid(); + + C.label("start"); + C.push("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"); // q + C.push("0x24"); + C.mload(); // k q + + + C.dup(1); // q k q + C.dup(0); // q q k q + C.push("0x04"); + C.mload(); // x q q k q + C.dup(3); // k x q q k q + C.addmod(); // t=x+k q k q + C.dup(1); // q t q k q + C.dup(0); // q q t q k q + C.dup(2); // t q q t q k q + C.dup(0); // t t q q t q k q + C.mulmod(); // a=t^2 q t q k q + C.dup(1); // q a q t q k q + C.dup(1); // a q a q t q k q + C.dup(0); // a a q a q t q k q + C.mulmod(); // b=t^4 a q t q k q + C.mulmod(); // c=t^6 t q k q + C.mulmod(); // r=t^7 k q + + for (let i=0; i8)) throw new Error("Invalid number of inputs. Must be 1<=nInputs<=8"); + const t = nInputs + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + + const C = new Contract(); + + function saveM() { + for (let i=0; i=nRoundsP+nRoundsF/2)) { + for (let j=0; j { + res[k] = unsringifyConstants(Fr, o[k]); + }); + return res; + } else { + return o; + } +} + +async function poseidon_reference_buildPoseidon() { + const bn128 = await getCurveFromName("bn128", true); + + const F = bn128.Fr; + + // Parameters are generated by a reference script https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/generate_parameters_grain.sage + // Used like so: sage generate_parameters_grain.sage 1 0 254 2 8 56 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 + const {C, M} = unsringifyConstants(F, poseidonConstants); + + // Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8) + // Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py + // And rounded up to nearest integer that divides by t + const N_ROUNDS_F = 8; + const N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68]; + + const pow5 = a => F.mul(a, F.square(F.square(a, a))); + + function poseidon(inputs, initState, nOut) { + assert(inputs.length > 0); + assert(inputs.length <= N_ROUNDS_P.length); + + const t = inputs.length + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + + if (initState) { + initState = F.e(initState); + } else { + initState = F.zero; + } + nOut = nOut || 1; + + let state = [initState, ...inputs.map(a => F.e(a))]; + for (let r = 0; r < nRoundsF + nRoundsP; r++) { + state = state.map((a, i) => F.add(a, C[t - 2][r * t + i])); + + if (r < nRoundsF / 2 || r >= nRoundsF / 2 + nRoundsP) { + state = state.map(a => pow5(a)); + } else { + state[0] = pow5(state[0]); + } + + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[t - 2][i][j], a)), F.zero) + ); + } + if (nOut == 1) { + return state[0] + } else { + return state.slice(0, nOut); + } + } + + poseidon.F = F; + return poseidon; +} + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/poseidon_opt.js +// Parameters are generated by a reference script https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/generate_parameters_grain.sage +// Used like so: sage generate_parameters_grain.sage 1 0 254 2 8 56 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 + +// Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8) +// Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py +// And rounded up to nearest integer that divides by t + +// Optimization is taken from https://github.com/filecoin-project/neptune + + + + + + +function poseidon_opt_unsringifyConstants(Fr, o) { + if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) { + return Fr.e(o); + } else if ((typeof(o) == "string") && (/^0x[0-9a-fA-F]+$/.test(o) )) { + return Fr.e(o); + } else if (Array.isArray(o)) { + return o.map(poseidon_opt_unsringifyConstants.bind(null, Fr)); + } else if (typeof o == "object") { + if (o===null) return null; + const res = {}; + const keys = Object.keys(o); + keys.forEach( (k) => { + res[k] = poseidon_opt_unsringifyConstants(Fr, o[k]); + }); + return res; + } else { + return o; + } +} + +async function poseidon_opt_buildPoseidon() { + const bn128 = await getCurveFromName("bn128", true); + + const F = bn128.Fr; + + const opt = poseidon_opt_unsringifyConstants(F, poseidonConstants); + + const N_ROUNDS_F = 8; + const N_ROUNDS_P = [56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68]; + + const pow5 = a => F.mul(a, F.square(F.square(a, a))); + + function poseidon(inputs, initState, nOut) { + assert(inputs.length > 0); + assert(inputs.length <= N_ROUNDS_P.length); + + if (initState) { + initState = F.e(initState); + } else { + initState = F.zero; + } + nOut = nOut || 1; + + + const t = inputs.length + 1; + const nRoundsF = N_ROUNDS_F; + const nRoundsP = N_ROUNDS_P[t - 2]; + const C = opt.C[t-2]; + const S = opt.S[t-2]; + const M = opt.M[t-2]; + const P = opt.P[t-2]; + + let state = [initState, ...inputs.map(a => F.e(a))]; + + state = state.map((a, i) => F.add(a, C[i])); + + for (let r = 0; r < nRoundsF/2-1; r++) { + state = state.map(a => pow5(a)); + state = state.map((a, i) => F.add(a, C[(r +1)* t +i])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + } + state = state.map(a => pow5(a)); + state = state.map((a, i) => F.add(a, C[(nRoundsF/2-1 +1)* t +i])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(P[j][i], a)), F.zero) + ); + for (let r = 0; r < nRoundsP; r++) { + state[0] = pow5(state[0]); + state[0] = F.add(state[0], C[(nRoundsF/2 +1)*t + r]); + + + const s0 = state.reduce((acc, a, j) => { + return F.add(acc, F.mul(S[(t*2-1)*r+j], a)); + }, F.zero); + for (let k=1; k pow5(a)); + state = state.map((a, i) => F.add(a, C[ (nRoundsF/2 +1)*t + nRoundsP + r*t + i ])); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + } + state = state.map(a => pow5(a)); + state = state.map((_, i) => + state.reduce((acc, a, j) => F.add(acc, F.mul(M[j][i], a)), F.zero) + ); + + if (nOut == 1) { + return state[0] + } else { + return state.slice(0, nOut); + } + } + + poseidon.F = F; + return poseidon; +} + + + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/smt_hashes_poseidon.js + + + + +async function smt_hashes_poseidon_getHashes() { + const bn128 = await getCurveFromName("bn128", true); + const poseidon = await buildPoseidon(); + return { + hash0: function (left, right) { + return poseidon([left, right]); + }, + hash1: function(key, value) { + return poseidon([key, value, bn128.Fr.one]); + }, + F: bn128.Fr + } +} + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/src/smt.js + + + + +async function buildSMT(db, root) { + + const {hash0, hash1,F} = await getHashes(); + + return new SMT(db, root, hash0, hash1, F); +} + +class SMT { + + constructor(db, root, hash0, hash1, F) { + this.db = db; + this.root = root; + this.hash0 = hash0; + this.hash1 = hash1; + this.F = F; + } + + _splitBits(_key) { + const F = this.F; + const res = Scalar.bits(F.toObject(_key)); + + while (res.length<256) res.push(false); + + return res; + } + + async update(_key, _newValue) { + const F = this.F; + const key = F.e(_key); + const newValue = F.e(_newValue); + + const resFind = await this.find(key); + const res = {}; + res.oldRoot = this.root; + res.oldKey = key; + res.oldValue = resFind.foundValue; + res.newKey = key; + res.newValue = newValue; + res.siblings = resFind.siblings; + + const ins = []; + const dels = []; + + let rtOld = this.hash1(key, resFind.foundValue); + let rtNew = this.hash1(key, newValue); + ins.push([rtNew, [1, key, newValue ]]); + dels.push(rtOld); + + const keyBits = this._splitBits(key); + for (let level = resFind.siblings.length-1; level >=0; level--) { + let oldNode, newNode; + const sibling = resFind.siblings[level]; + if (keyBits[level]) { + oldNode = [sibling, rtOld]; + newNode = [sibling, rtNew]; + } else { + oldNode = [rtOld, sibling]; + newNode = [rtNew, sibling]; + } + rtOld = this.hash0(oldNode[0], oldNode[1]); + rtNew = this.hash0(newNode[0], newNode[1]); + dels.push(rtOld); + ins.push([rtNew, newNode]); + } + + res.newRoot = rtNew; + + await this.db.multiDel(dels); + await this.db.multiIns(ins); + await this.db.setRoot(rtNew); + this.root = rtNew; + + return res; + } + + async delete(_key) { + const F = this.F; + const key = F.e(_key); + + const resFind = await this.find(key); + if (!resFind.found) throw new Error("Key does not exists"); + + const res = { + siblings: [], + delKey: key, + delValue: resFind.foundValue + }; + + const dels = []; + const ins = []; + let rtOld = this.hash1(key, resFind.foundValue); + let rtNew; + dels.push(rtOld); + + let mixed; + if (resFind.siblings.length > 0) { + const record = await this.db.get(resFind.siblings[resFind.siblings.length - 1]); + if ((record.length == 3)&&(F.eq(record[0], F.one))) { + mixed = false; + res.oldKey = record[1]; + res.oldValue = record[2]; + res.isOld0 = false; + rtNew = resFind.siblings[resFind.siblings.length - 1]; + } else if (record.length == 2) { + mixed = true; + res.oldKey = key; + res.oldValue = F.zero; + res.isOld0 = true; + rtNew = F.zero; + } else { + throw new Error("Invalid node. Database corrupted"); + } + } else { + rtNew = F.zero; + res.oldKey = key; + res.oldValue = F.zero; + res.isOld0 = true; + } + + const keyBits = this._splitBits(key); + + for (let level = resFind.siblings.length-1; level >=0; level--) { + let newSibling = resFind.siblings[level]; + if ((level == resFind.siblings.length-1)&&(!res.isOld0)) { + newSibling = F.zero; + } + const oldSibling = resFind.siblings[level]; + if (keyBits[level]) { + rtOld = this.hash0(oldSibling, rtOld); + } else { + rtOld = this.hash0(rtOld, oldSibling); + } + dels.push(rtOld); + if (!F.isZero(newSibling)) { + mixed = true; + } + + if (mixed) { + res.siblings.unshift(resFind.siblings[level]); + let newNode; + if (keyBits[level]) { + newNode = [newSibling, rtNew]; + } else { + newNode = [rtNew, newSibling]; + } + rtNew = this.hash0(newNode[0], newNode[1]); + ins.push([rtNew, newNode]); + } + } + + await this.db.multiIns(ins); + await this.db.setRoot(rtNew); + this.root = rtNew; + await this.db.multiDel(dels); + + res.newRoot = rtNew; + res.oldRoot = rtOld; + + return res; + } + + async insert(_key, _value) { + const F = this.F; + const key = F.e(_key); + const value = F.e(_value); + let addedOne = false; + const res = {}; + res.oldRoot = this.root; + const newKeyBits = this._splitBits(key); + + let rtOld; + + const resFind = await this.find(key); + + if (resFind.found) throw new Error("Key already exists"); + + res.siblings = resFind.siblings; + let mixed; + + if (!resFind.isOld0) { + const oldKeyits = this._splitBits(resFind.notFoundKey); + for (let i= res.siblings.length; oldKeyits[i] == newKeyBits[i]; i++) { + res.siblings.push(F.zero); + } + rtOld = this.hash1(resFind.notFoundKey, resFind.notFoundValue); + res.siblings.push(rtOld); + addedOne = true; + mixed = false; + } else if (res.siblings.length >0) { + mixed = true; + rtOld = F.zero; + } + + const inserts = []; + const dels = []; + + let rt = this.hash1(key, value); + inserts.push([rt,[1, key, value]] ); + + for (let i=res.siblings.length-1; i>=0; i--) { + if ((i0) && (F.isZero(res.siblings[res.siblings.length-1]))) { + res.siblings.pop(); + } + res.oldKey = resFind.notFoundKey; + res.oldValue = resFind.notFoundValue; + res.newRoot = rt; + res.isOld0 = resFind.isOld0; + + + await this.db.multiIns(inserts); + await this.db.setRoot(rt); + this.root = rt; + await this.db.multiDel(dels); + + return res; + } + + async find(_key) { + const key = this.F.e(_key); + const keyBits = this._splitBits(key); + return await this._find(key, keyBits, this.root, 0); + } + + async _find(key, keyBits, root, level) { + const F = this.F; + if (typeof root === "undefined") root = this.root; + + let res; + if (F.isZero(root)) { + res = { + found: false, + siblings: [], + notFoundKey: key, + notFoundValue: F.zero, + isOld0: true + }; + return res; + } + + const record = await this.db.get(root); + + if ((record.length==3)&&(F.eq(record[0],F.one))) { + if (F.eq(record[1],key)) { + res = { + found: true, + siblings: [], + foundValue: record[2], + isOld0: false + }; + } else { + res = { + found: false, + siblings: [], + notFoundKey: record[1], + notFoundValue: record[2], + isOld0: false + }; + } + } else { + if (keyBits[level] == 0) { + res = await this._find(key, keyBits, record[0], level+1); + res.siblings.unshift(record[1]); + } else { + res = await this._find(key, keyBits, record[1], level+1); + res.siblings.unshift(record[0]); + } + } + return res; + } +} + + +async function newMemEmptyTrie() { + const {hash0, hash1,F} = await getHashes(); + const db = new SMTMemDB(F); + const rt = await db.getRoot(); + const smt = new SMT(db, rt, hash0, hash1, F); + return smt; +} + +;// CONCATENATED MODULE: ./node_modules/circomlibjs/main.js + + + + + + +const mimc7Contract=(/* unused pure expression or super */ null && (_mimc7Contract)); + + + +const mimcSpongecontract=(/* unused pure expression or super */ null && (_mimcSpongeContract)); + + + + + +const poseidonContract=(/* unused pure expression or super */ null && (_poseidonContract)); + + + + + + + + + +;// CONCATENATED MODULE: ./src/mimc.ts + +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +class Mimc { + constructor() { + this.mimcPromise = this.initMimc(); + } + initMimc() { + return __async(this, null, function* () { + this.sponge = yield mimcsponge_buildMimcSponge(); + this.hash = (left, right) => { + var _a, _b; + return (_b = this.sponge) == null ? void 0 : _b.F.toString((_a = this.sponge) == null ? void 0 : _a.multiHash([BigInt(left), BigInt(right)])); + }; + }); + } + getHash() { + return __async(this, null, function* () { + yield this.mimcPromise; + return { + sponge: this.sponge, + hash: this.hash + }; + }); + } +} +const mimc = new Mimc(); + +// EXTERNAL MODULE: ./node_modules/bn.js/lib/bn.js +var bn = __webpack_require__(9404); +;// CONCATENATED MODULE: ./src/utils.ts +/* provided dependency */ var utils_process = __webpack_require__(5606); + + + +BigInt.prototype.toJSON = function() { + return this.toString(); +}; +const isNode = !utils_process.browser && typeof globalThis.window === "undefined"; +const utils_crypto = isNode ? crypto_browserify.webcrypto : globalThis.crypto; +const chunk = (arr, size) => [...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i)); +function utils_sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function validateUrl(url, protocols) { + try { + const parsedUrl = new URL(url); + if (protocols && protocols.length) { + return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol); + } + return true; + } catch (e) { + return false; + } +} +function concatBytes(...arrays) { + const totalSize = arrays.reduce((acc, e) => acc + e.length, 0); + const merged = new Uint8Array(totalSize); + arrays.forEach((array, i, arrays2) => { + const offset = arrays2.slice(0, i).reduce((acc, e) => acc + e.length, 0); + merged.set(array, offset); + }); + return merged; +} +function bufferToBytes(b) { + return new Uint8Array(b.buffer); +} +function bytesToBase64(bytes) { + return btoa(String.fromCharCode.apply(null, Array.from(bytes))); +} +function base64ToBytes(base64) { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} +function bytesToHex(bytes) { + return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes(hexString) { + if (hexString.slice(0, 2) === "0x") { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function bytesToBN(bytes) { + return BigInt(bytesToHex(bytes)); +} +function bnToBytes(bigint) { + let hexString = typeof bigint === "bigint" ? bigint.toString(16) : bigint; + if (hexString.startsWith("0x")) { + hexString = hexString.replace("0x", ""); + } + if (hexString.length % 2 !== 0) { + hexString = "0" + hexString; + } + return Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); +} +function leBuff2Int(bytes) { + return new BN(bytes, 16, "le"); +} +function src_utils_leInt2Buff(bigint) { + return Uint8Array.from(new BN(bigint).toArray("le", 31)); +} +function toFixedHex(numberish, length = 32) { + return "0x" + BigInt(numberish).toString(16).padStart(length * 2, "0"); +} +function toFixedLength(string, length = 32) { + string = string.replace("0x", ""); + return "0x" + string.padStart(length * 2, "0"); +} +function rBigInt(nbytes = 31) { + return bytesToBN(utils_crypto.getRandomValues(new Uint8Array(nbytes))); +} +function bigIntReplacer(key, value) { + return typeof value === "bigint" ? value.toString() : value; +} +function substring(str, length = 10) { + if (str.length < length * 2) { + return str; + } + return `${str.substring(0, length)}...${str.substring(str.length - length)}`; +} + +;// CONCATENATED MODULE: ./src/merkleTreeWorker.ts + +var merkleTreeWorker_async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + + + + +function nodePostWork() { + return merkleTreeWorker_async(this, null, function* () { + const { hash: hashFunction } = yield mimc.getHash(); + const { merkleTreeHeight, edge, elements, zeroElement } = (worker_threads_ignored_default()).workerData; + if (edge) { + const merkleTree2 = new lib.PartialMerkleTree(merkleTreeHeight, edge, elements, { + zeroElement, + hashFunction + }); + worker_threads_ignored_default().parentPort.postMessage(merkleTree2.toString()); + return; + } + const merkleTree = new lib.MerkleTree(merkleTreeHeight, elements, { + zeroElement, + hashFunction + }); + worker_threads_ignored_default().parentPort.postMessage(merkleTree.toString()); + }); +} +if (isNode && (worker_threads_ignored_default())) { + nodePostWork(); +} else if (!isNode && typeof addEventListener === "function" && typeof postMessage === "function") { + addEventListener("message", (e) => merkleTreeWorker_async(undefined, null, function* () { + let data; + if (e.data) { + data = e.data; + } else { + data = e; + } + const { hash: hashFunction } = yield mimc.getHash(); + const { merkleTreeHeight, edge, elements, zeroElement } = data; + if (edge) { + const merkleTree2 = new lib.PartialMerkleTree(merkleTreeHeight, edge, elements, { + zeroElement, + hashFunction + }); + postMessage(merkleTree2.toString()); + return; + } + const merkleTree = new lib.MerkleTree(merkleTreeHeight, elements, { + zeroElement, + hashFunction + }); + postMessage(merkleTree.toString()); + })); +} else { + throw new Error("This browser / environment does not support workers!"); +} + +})(); + +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/dist/mimc.d.ts b/dist/mimc.d.ts new file mode 100644 index 0000000..11a506f --- /dev/null +++ b/dist/mimc.d.ts @@ -0,0 +1,14 @@ +import { MimcSponge } from 'circomlibjs'; +import type { Element, HashFunction } from '@tornado/fixed-merkle-tree'; +export declare class Mimc { + sponge?: MimcSponge; + hash?: HashFunction; + mimcPromise: Promise; + constructor(); + initMimc(): Promise; + getHash(): Promise<{ + sponge: MimcSponge | undefined; + hash: HashFunction | undefined; + }>; +} +export declare const mimc: Mimc; diff --git a/dist/multicall.d.ts b/dist/multicall.d.ts new file mode 100644 index 0000000..69e1f8a --- /dev/null +++ b/dist/multicall.d.ts @@ -0,0 +1,11 @@ +import { BaseContract, Interface } from 'ethers'; +import { Multicall } from './typechain'; +export interface Call3 { + contract?: BaseContract; + address?: string; + interface?: Interface; + name: string; + params?: any[]; + allowFailure?: boolean; +} +export declare function multicall(Multicall: Multicall, calls: Call3[]): Promise; diff --git a/dist/networkConfig.d.ts b/dist/networkConfig.d.ts new file mode 100644 index 0000000..1789ac2 --- /dev/null +++ b/dist/networkConfig.d.ts @@ -0,0 +1,116 @@ +/** + * Type of default supported networks + */ +export declare enum NetId { + MAINNET = 1, + BSC = 56, + POLYGON = 137, + OPTIMISM = 10, + ARBITRUM = 42161, + GNOSIS = 100, + AVALANCHE = 43114, + SEPOLIA = 11155111 +} +export type NetIdType = NetId | number; +export interface RpcUrl { + name: string; + url: string; +} +export type RpcUrls = { + [key in string]: RpcUrl; +}; +export interface SubgraphUrl { + name: string; + url: string; +} +export type SubgraphUrls = { + [key in string]: SubgraphUrl; +}; +export type TornadoInstance = { + instanceAddress: { + [key in string]: string; + }; + optionalInstances?: string[]; + tokenAddress?: string; + tokenGasLimit?: number; + symbol: string; + decimals: number; + gasLimit?: number; +}; +export type TokenInstances = { + [key in string]: TornadoInstance; +}; +export type Config = { + rpcCallRetryAttempt?: number; + gasPrices: { + instant: number; + fast?: number; + standard?: number; + low?: number; + maxPriorityFeePerGas?: number; + }; + nativeCurrency: string; + currencyName: string; + explorerUrl: string; + merkleTreeHeight: number; + emptyElement: string; + networkName: string; + deployedBlock: number; + rpcUrls: RpcUrls; + multicallContract: string; + routerContract: string; + echoContract: string; + offchainOracleContract?: string; + tornContract?: string; + governanceContract?: string; + stakingRewardsContract?: string; + registryContract?: string; + aggregatorContract?: string; + reverseRecordsContract?: string; + gasPriceOracleContract?: string; + gasStationApi?: string; + ovmGasPriceOracleContract?: string; + tornadoSubgraph: string; + registrySubgraph?: string; + governanceSubgraph?: string; + subgraphs: SubgraphUrls; + tokens: TokenInstances; + optionalTokens?: string[]; + ensSubdomainKey: string; + pollInterval: number; + constants: { + GOVERNANCE_BLOCK?: number; + NOTE_ACCOUNT_BLOCK?: number; + ENCRYPTED_NOTES_BLOCK?: number; + REGISTRY_BLOCK?: number; + MINING_BLOCK_TIME?: number; + }; +}; +export type networkConfig = { + [key in NetIdType]: Config; +}; +export declare const defaultConfig: networkConfig; +export declare const enabledChains: number[]; +/** + * Custom config object to extend default config + * + * Inspired by getUrlFunc from ethers.js + * https://github.com/ethers-io/ethers.js/blob/v6/src.ts/utils/fetch.ts#L59 + */ +export declare let customConfig: networkConfig; +/** + * Add or override existing network config object + * + * Could be also called on the UI hook so that the UI could allow people to use custom privacy pools + */ +export declare function addNetwork(newConfig: networkConfig): void; +export declare function getNetworkConfig(): networkConfig; +export declare function getConfig(netId: NetIdType): Config; +export declare function getInstanceByAddress({ netId, address }: { + netId: NetIdType; + address: string; +}): { + amount: string; + currency: string; +} | undefined; +export declare function getSubdomains(): string[]; diff --git a/dist/parser.d.ts b/dist/parser.d.ts new file mode 100644 index 0000000..35da7f2 --- /dev/null +++ b/dist/parser.d.ts @@ -0,0 +1,10 @@ +export declare function parseNumber(value?: string | number): number; +export declare function parseUrl(value?: string): string; +export declare function parseRelayer(value?: string): string; +export declare function parseAddress(value?: string): string; +export declare function parseMnemonic(value?: string): string; +export declare function parseKey(value?: string): string; +/** + * Recovery key shouldn't have a 0x prefix (Also this is how the UI generates) + */ +export declare function parseRecoveryKey(value?: string): string; diff --git a/dist/pedersen.d.ts b/dist/pedersen.d.ts new file mode 100644 index 0000000..18eef7a --- /dev/null +++ b/dist/pedersen.d.ts @@ -0,0 +1,12 @@ +import { BabyJub, PedersenHash, Point } from 'circomlibjs'; +export declare class Pedersen { + pedersenHash?: PedersenHash; + babyJub?: BabyJub; + pedersenPromise: Promise; + constructor(); + initPedersen(): Promise; + unpackPoint(buffer: Uint8Array): Promise; + toStringBuffer(buffer: Uint8Array): string; +} +export declare const pedersen: Pedersen; +export declare function buffPedersenHash(buffer: Uint8Array): Promise; diff --git a/dist/prices.d.ts b/dist/prices.d.ts new file mode 100644 index 0000000..52b33cf --- /dev/null +++ b/dist/prices.d.ts @@ -0,0 +1,9 @@ +import { type Provider } from 'ethers'; +import type { OffchainOracle, Multicall } from './typechain'; +export declare class TokenPriceOracle { + oracle?: OffchainOracle; + multicall: Multicall; + provider: Provider; + constructor(provider: Provider, multicall: Multicall, oracle?: OffchainOracle); + fetchPrices(tokens: string[]): Promise; +} diff --git a/dist/providers.d.ts b/dist/providers.d.ts new file mode 100644 index 0000000..d85ddd1 --- /dev/null +++ b/dist/providers.d.ts @@ -0,0 +1,93 @@ +/// +/// +/// +import type { EventEmitter } from 'stream'; +import type { RequestOptions } from 'http'; +import { JsonRpcApiProvider, JsonRpcProvider, Wallet, FetchGetUrlFunc, Provider, SigningKey, TransactionRequest, JsonRpcSigner, BrowserProvider, Networkish, Eip1193Provider, VoidSigner, FetchUrlFeeDataNetworkPlugin } from 'ethers'; +import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch'; +import type { Config, NetIdType } from './networkConfig'; +declare global { + interface Window { + ethereum?: Eip1193Provider & EventEmitter; + } +} +export declare const defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0"; +export declare const fetch: nodeFetch; +export type nodeFetch = (url: RequestInfo, init?: RequestInit) => Promise; +export type fetchDataOptions = RequestInit & { + headers?: HeadersInit | any; + maxRetry?: number; + retryOn?: number; + userAgent?: string; + timeout?: number; + proxy?: string; + torPort?: number; + debug?: Function; + returnResponse?: boolean; +}; +export type NodeAgent = RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']); +export declare function getHttpAgent({ fetchUrl, proxyUrl, torPort, retry, }: { + fetchUrl: string; + proxyUrl?: string; + torPort?: number; + retry: number; +}): NodeAgent | undefined; +export declare function fetchData(url: string, options?: fetchDataOptions): Promise; +export declare const fetchGetUrlFunc: (options?: fetchDataOptions) => FetchGetUrlFunc; +export type getProviderOptions = fetchDataOptions & { + pollingInterval?: number; + gasPriceOracle?: string; + gasStationApi?: string; +}; +export declare function getGasOraclePlugin(networkKey: string, fetchOptions?: getProviderOptions): FetchUrlFeeDataNetworkPlugin; +export declare function getProvider(rpcUrl: string, fetchOptions?: getProviderOptions): Promise; +export declare function getProviderWithNetId(netId: NetIdType, rpcUrl: string, config: Config, fetchOptions?: getProviderOptions): JsonRpcProvider; +export declare const populateTransaction: (signer: TornadoWallet | TornadoVoidSigner | TornadoRpcSigner, tx: TransactionRequest) => Promise; +export type TornadoWalletOptions = { + gasPriceBump?: number; + gasLimitBump?: number; + gasFailover?: boolean; + bumpNonce?: boolean; +}; +export declare class TornadoWallet extends Wallet { + nonce?: number | null; + gasPriceBump: number; + gasLimitBump: number; + gasFailover: boolean; + bumpNonce: boolean; + constructor(key: string | SigningKey, provider?: null | Provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce }?: TornadoWalletOptions); + static fromMnemonic(mneomnic: string, provider: Provider, index?: number, options?: TornadoWalletOptions): TornadoWallet; + populateTransaction(tx: TransactionRequest): Promise>; +} +export declare class TornadoVoidSigner extends VoidSigner { + nonce?: number | null; + gasPriceBump: number; + gasLimitBump: number; + gasFailover: boolean; + bumpNonce: boolean; + constructor(address: string, provider?: null | Provider, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce }?: TornadoWalletOptions); + populateTransaction(tx: TransactionRequest): Promise>; +} +export declare class TornadoRpcSigner extends JsonRpcSigner { + nonce?: number | null; + gasPriceBump: number; + gasLimitBump: number; + gasFailover: boolean; + bumpNonce: boolean; + constructor(provider: JsonRpcApiProvider, address: string, { gasPriceBump, gasLimitBump, gasFailover, bumpNonce }?: TornadoWalletOptions); + sendUncheckedTransaction(tx: TransactionRequest): Promise; +} +export type connectWalletFunc = (...args: any[]) => Promise; +export type handleWalletFunc = (...args: any[]) => void; +export type TornadoBrowserProviderOptions = TornadoWalletOptions & { + webChainId?: NetIdType; + connectWallet?: connectWalletFunc; + handleNetworkChanges?: handleWalletFunc; + handleAccountChanges?: handleWalletFunc; + handleAccountDisconnect?: handleWalletFunc; +}; +export declare class TornadoBrowserProvider extends BrowserProvider { + options?: TornadoBrowserProviderOptions; + constructor(ethereum: Eip1193Provider, network?: Networkish, options?: TornadoBrowserProviderOptions); + getSigner(address: string): Promise; +} diff --git a/dist/relayerClient.d.ts b/dist/relayerClient.d.ts new file mode 100644 index 0000000..351ff41 --- /dev/null +++ b/dist/relayerClient.d.ts @@ -0,0 +1,128 @@ +import type { Aggregator } from '@tornado/contracts'; +import type { RelayerStructOutput } from '@tornado/contracts/dist/contracts/Governance/Aggregator/Aggregator'; +import { NetIdType, Config } from './networkConfig'; +import { fetchDataOptions } from './providers'; +import type { snarkProofs } from './websnark'; +export declare const MIN_STAKE_BALANCE: bigint; +export interface RelayerParams { + ensName: string; + relayerAddress?: string; +} +export interface Relayer { + netId: NetIdType; + url: string; + hostname: string; + rewardAccount: string; + instances: string[]; + gasPrice?: number; + ethPrices?: { + [key in string]: string; + }; + currentQueue: number; + tornadoServiceFee: number; +} +export type RelayerInfo = Relayer & { + ensName: string; + stakeBalance: bigint; + relayerAddress: string; +}; +export type RelayerError = { + hostname: string; + relayerAddress?: string; + errorMessage?: string; +}; +export interface RelayerStatus { + url: string; + rewardAccount: string; + instances: { + [key in string]: { + instanceAddress: { + [key in string]: string; + }; + tokenAddress?: string; + symbol: string; + decimals: number; + }; + }; + gasPrices?: { + fast: number; + additionalProperties?: number; + }; + netId: NetIdType; + ethPrices?: { + [key in string]: string; + }; + tornadoServiceFee: number; + latestBlock?: number; + version: string; + health: { + status: string; + error: string; + errorsLog: any[]; + }; + currentQueue: number; +} +export interface RelayerTornadoWithdraw { + id?: string; + error?: string; +} +export interface RelayerTornadoJobs { + error?: string; + id: string; + type?: string; + status: string; + contract?: string; + proof?: string; + args?: string[]; + txHash?: string; + confirmations?: number; + failedReason?: string; +} +export interface semanticVersion { + major: string; + minor: string; + patch: string; + prerelease?: string; + buildmetadata?: string; +} +export declare function parseSemanticVersion(version: string): semanticVersion; +export declare function isRelayerUpdated(relayerVersion: string, netId: NetIdType): boolean; +export declare function calculateScore({ stakeBalance, tornadoServiceFee }: RelayerInfo, minFee?: number, maxFee?: number): bigint; +export declare function getWeightRandom(weightsScores: bigint[], random: bigint): number; +export type RelayerInstanceList = { + [key in string]: { + instanceAddress: { + [key in string]: string; + }; + }; +}; +export declare function getSupportedInstances(instanceList: RelayerInstanceList): string[]; +export declare function pickWeightedRandomRelayer(relayers: RelayerInfo[], netId: NetIdType): RelayerInfo; +export interface RelayerClientConstructor { + netId: NetIdType; + config: Config; + Aggregator: Aggregator; + fetchDataOptions?: fetchDataOptions; +} +export type RelayerClientWithdraw = snarkProofs & { + contract: string; +}; +export declare class RelayerClient { + netId: NetIdType; + config: Config; + Aggregator: Aggregator; + selectedRelayer?: Relayer; + fetchDataOptions?: fetchDataOptions; + constructor({ netId, config, Aggregator, fetchDataOptions }: RelayerClientConstructor); + askRelayerStatus({ hostname, relayerAddress, }: { + hostname: string; + relayerAddress?: string; + }): Promise; + filterRelayer(curr: RelayerStructOutput, relayer: RelayerParams, subdomains: string[], debugRelayer?: boolean): Promise; + getValidRelayers(relayers: RelayerParams[], subdomains: string[], debugRelayer?: boolean): Promise<{ + validRelayers: RelayerInfo[]; + invalidRelayers: RelayerError[]; + }>; + pickWeightedRandomRelayer(relayers: RelayerInfo[]): RelayerInfo; + tornadoWithdraw({ contract, proof, args }: RelayerClientWithdraw): Promise; +} diff --git a/dist/schemas/index.d.ts b/dist/schemas/index.d.ts new file mode 100644 index 0000000..b3c1810 --- /dev/null +++ b/dist/schemas/index.d.ts @@ -0,0 +1,4 @@ +import Ajv from 'ajv'; +export declare const ajv: Ajv; +export * from './status'; +export * from './jobs'; diff --git a/dist/schemas/jobs.d.ts b/dist/schemas/jobs.d.ts new file mode 100644 index 0000000..15a2220 --- /dev/null +++ b/dist/schemas/jobs.d.ts @@ -0,0 +1,40 @@ +export type jobsSchema = { + type: string; + properties: { + error: { + type: string; + }; + id: { + type: string; + }; + type: { + type: string; + }; + status: { + type: string; + }; + contract: { + type: string; + }; + proof: { + type: string; + }; + args: { + type: string; + items: { + type: string; + }; + }; + txHash: { + type: string; + }; + confirmations: { + type: string; + }; + failedReason: { + type: string; + }; + }; + required: string[]; +}; +export declare const jobsSchema: jobsSchema; diff --git a/dist/schemas/status.d.ts b/dist/schemas/status.d.ts new file mode 100644 index 0000000..f5e3b4e --- /dev/null +++ b/dist/schemas/status.d.ts @@ -0,0 +1,92 @@ +import { Config, NetIdType } from '../networkConfig'; +export type statusInstanceType = { + type: string; + properties: { + instanceAddress: { + type: string; + properties: { + [key in string]: typeof addressType; + }; + required: string[]; + }; + tokenAddress?: typeof addressType; + symbol?: { + enum: string[]; + }; + decimals: { + enum: number[]; + }; + }; + required: string[]; +}; +export type statusInstancesType = { + type: string; + properties: { + [key in string]: statusInstanceType; + }; + required: string[]; +}; +export type statusEthPricesType = { + type: string; + properties: { + [key in string]: typeof bnType; + }; + required?: string[]; +}; +export type statusSchema = { + type: string; + properties: { + rewardAccount: typeof addressType; + instances?: statusInstancesType; + gasPrices: { + type: string; + properties: { + [key in string]: { + type: string; + }; + }; + required: string[]; + }; + netId: { + type: string; + }; + ethPrices?: statusEthPricesType; + tornadoServiceFee?: { + type: string; + maximum: number; + minimum: number; + }; + latestBlock?: { + type: string; + }; + version: { + type: string; + }; + health: { + type: string; + properties: { + status: { + const: string; + }; + error: { + type: string; + }; + }; + required: string[]; + }; + currentQueue: { + type: string; + }; + }; + required: string[]; +}; +declare const addressType: { + type: string; + pattern: string; +}; +declare const bnType: { + type: string; + BN: boolean; +}; +export declare function getStatusSchema(netId: NetIdType, config: Config): statusSchema; +export {}; diff --git a/dist/tokens.d.ts b/dist/tokens.d.ts new file mode 100644 index 0000000..cb7d22f --- /dev/null +++ b/dist/tokens.d.ts @@ -0,0 +1,16 @@ +import { Provider } from 'ethers'; +import { Multicall } from './typechain'; +export interface tokenBalances { + address: string; + name: string; + symbol: string; + decimals: number; + balance: bigint; +} +export declare function getTokenBalances({ provider, Multicall, currencyName, userAddress, tokenAddresses, }: { + provider: Provider; + Multicall: Multicall; + currencyName: string; + userAddress: string; + tokenAddresses: string[]; +}): Promise; diff --git a/dist/treeCache.d.ts b/dist/treeCache.d.ts new file mode 100644 index 0000000..926c37a --- /dev/null +++ b/dist/treeCache.d.ts @@ -0,0 +1,35 @@ +/** + * Create tree cache file from node.js + * + * Only works for node.js, modified from https://github.com/tornadocash/tornado-classic-ui/blob/master/scripts/updateTree.js + */ +import { MerkleTree } from '@tornado/fixed-merkle-tree'; +import { DepositsEvents } from './events'; +import type { NetIdType } from './networkConfig'; +export interface TreeCacheConstructor { + netId: NetIdType; + amount: string; + currency: string; + userDirectory: string; + PARTS_COUNT?: number; + LEAVES?: number; + zeroElement?: string; +} +export interface treeMetadata { + blockNumber: number; + logIndex: number; + transactionHash: string; + timestamp: number; + from: string; + leafIndex: number; +} +export declare class TreeCache { + netId: NetIdType; + amount: string; + currency: string; + userDirectory: string; + PARTS_COUNT: number; + constructor({ netId, amount, currency, userDirectory, PARTS_COUNT }: TreeCacheConstructor); + getInstanceName(): string; + createTree(events: DepositsEvents[], tree: MerkleTree): Promise; +} diff --git a/dist/typechain/ENS.d.ts b/dist/typechain/ENS.d.ts new file mode 100644 index 0000000..9f65210 --- /dev/null +++ b/dist/typechain/ENS.d.ts @@ -0,0 +1,423 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, EventFragment, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedLogDescription, TypedListener, TypedContractMethod } from "./common"; +export interface ENSInterface extends Interface { + getFunction(nameOrSignature: "supportsInterface" | "setText" | "interfaceImplementer" | "ABI" | "setPubkey" | "setContenthash" | "addr(bytes32)" | "addr(bytes32,uint256)" | "setAuthorisation" | "text" | "setABI" | "name" | "setName" | "setAddr(bytes32,uint256,bytes)" | "setAddr(bytes32,address)" | "contenthash" | "pubkey" | "setInterface" | "authorisations"): FunctionFragment; + getEvent(nameOrSignatureOrTopic: "AuthorisationChanged" | "TextChanged" | "PubkeyChanged" | "NameChanged" | "InterfaceChanged" | "ContenthashChanged" | "AddrChanged" | "AddressChanged" | "ABIChanged"): EventFragment; + encodeFunctionData(functionFragment: "supportsInterface", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "setText", values: [BytesLike, string, string]): string; + encodeFunctionData(functionFragment: "interfaceImplementer", values: [BytesLike, BytesLike]): string; + encodeFunctionData(functionFragment: "ABI", values: [BytesLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "setPubkey", values: [BytesLike, BytesLike, BytesLike]): string; + encodeFunctionData(functionFragment: "setContenthash", values: [BytesLike, BytesLike]): string; + encodeFunctionData(functionFragment: "addr(bytes32)", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "addr(bytes32,uint256)", values: [BytesLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "setAuthorisation", values: [BytesLike, AddressLike, boolean]): string; + encodeFunctionData(functionFragment: "text", values: [BytesLike, string]): string; + encodeFunctionData(functionFragment: "setABI", values: [BytesLike, BigNumberish, BytesLike]): string; + encodeFunctionData(functionFragment: "name", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "setName", values: [BytesLike, string]): string; + encodeFunctionData(functionFragment: "setAddr(bytes32,uint256,bytes)", values: [BytesLike, BigNumberish, BytesLike]): string; + encodeFunctionData(functionFragment: "setAddr(bytes32,address)", values: [BytesLike, AddressLike]): string; + encodeFunctionData(functionFragment: "contenthash", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "pubkey", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "setInterface", values: [BytesLike, BytesLike, AddressLike]): string; + encodeFunctionData(functionFragment: "authorisations", values: [BytesLike, AddressLike, AddressLike]): string; + decodeFunctionResult(functionFragment: "supportsInterface", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setText", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "interfaceImplementer", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "ABI", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setPubkey", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setContenthash", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "addr(bytes32)", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "addr(bytes32,uint256)", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setAuthorisation", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "text", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setABI", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "name", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setName", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setAddr(bytes32,uint256,bytes)", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setAddr(bytes32,address)", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "contenthash", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "pubkey", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setInterface", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "authorisations", data: BytesLike): Result; +} +export declare namespace AuthorisationChangedEvent { + type InputTuple = [ + node: BytesLike, + owner: AddressLike, + target: AddressLike, + isAuthorised: boolean + ]; + type OutputTuple = [ + node: string, + owner: string, + target: string, + isAuthorised: boolean + ]; + interface OutputObject { + node: string; + owner: string; + target: string; + isAuthorised: boolean; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace TextChangedEvent { + type InputTuple = [node: BytesLike, indexedKey: string, key: string]; + type OutputTuple = [node: string, indexedKey: string, key: string]; + interface OutputObject { + node: string; + indexedKey: string; + key: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace PubkeyChangedEvent { + type InputTuple = [node: BytesLike, x: BytesLike, y: BytesLike]; + type OutputTuple = [node: string, x: string, y: string]; + interface OutputObject { + node: string; + x: string; + y: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace NameChangedEvent { + type InputTuple = [node: BytesLike, name: string]; + type OutputTuple = [node: string, name: string]; + interface OutputObject { + node: string; + name: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace InterfaceChangedEvent { + type InputTuple = [ + node: BytesLike, + interfaceID: BytesLike, + implementer: AddressLike + ]; + type OutputTuple = [ + node: string, + interfaceID: string, + implementer: string + ]; + interface OutputObject { + node: string; + interfaceID: string; + implementer: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace ContenthashChangedEvent { + type InputTuple = [node: BytesLike, hash: BytesLike]; + type OutputTuple = [node: string, hash: string]; + interface OutputObject { + node: string; + hash: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace AddrChangedEvent { + type InputTuple = [node: BytesLike, a: AddressLike]; + type OutputTuple = [node: string, a: string]; + interface OutputObject { + node: string; + a: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace AddressChangedEvent { + type InputTuple = [ + node: BytesLike, + coinType: BigNumberish, + newAddress: BytesLike + ]; + type OutputTuple = [ + node: string, + coinType: bigint, + newAddress: string + ]; + interface OutputObject { + node: string; + coinType: bigint; + newAddress: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace ABIChangedEvent { + type InputTuple = [node: BytesLike, contentType: BigNumberish]; + type OutputTuple = [node: string, contentType: bigint]; + interface OutputObject { + node: string; + contentType: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export interface ENS extends BaseContract { + connect(runner?: ContractRunner | null): ENS; + waitForDeployment(): Promise; + interface: ENSInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + supportsInterface: TypedContractMethod<[ + interfaceID: BytesLike + ], [ + boolean + ], "view">; + setText: TypedContractMethod<[ + node: BytesLike, + key: string, + value: string + ], [ + void + ], "nonpayable">; + interfaceImplementer: TypedContractMethod<[ + node: BytesLike, + interfaceID: BytesLike + ], [ + string + ], "view">; + ABI: TypedContractMethod<[ + node: BytesLike, + contentTypes: BigNumberish + ], [ + [bigint, string] + ], "view">; + setPubkey: TypedContractMethod<[ + node: BytesLike, + x: BytesLike, + y: BytesLike + ], [ + void + ], "nonpayable">; + setContenthash: TypedContractMethod<[ + node: BytesLike, + hash: BytesLike + ], [ + void + ], "nonpayable">; + "addr(bytes32)": TypedContractMethod<[node: BytesLike], [string], "view">; + "addr(bytes32,uint256)": TypedContractMethod<[ + node: BytesLike, + coinType: BigNumberish + ], [ + string + ], "view">; + setAuthorisation: TypedContractMethod<[ + node: BytesLike, + target: AddressLike, + isAuthorised: boolean + ], [ + void + ], "nonpayable">; + text: TypedContractMethod<[node: BytesLike, key: string], [string], "view">; + setABI: TypedContractMethod<[ + node: BytesLike, + contentType: BigNumberish, + data: BytesLike + ], [ + void + ], "nonpayable">; + name: TypedContractMethod<[node: BytesLike], [string], "view">; + setName: TypedContractMethod<[ + node: BytesLike, + name: string + ], [ + void + ], "nonpayable">; + "setAddr(bytes32,uint256,bytes)": TypedContractMethod<[ + node: BytesLike, + coinType: BigNumberish, + a: BytesLike + ], [ + void + ], "nonpayable">; + "setAddr(bytes32,address)": TypedContractMethod<[ + node: BytesLike, + a: AddressLike + ], [ + void + ], "nonpayable">; + contenthash: TypedContractMethod<[node: BytesLike], [string], "view">; + pubkey: TypedContractMethod<[ + node: BytesLike + ], [ + [string, string] & { + x: string; + y: string; + } + ], "view">; + setInterface: TypedContractMethod<[ + node: BytesLike, + interfaceID: BytesLike, + implementer: AddressLike + ], [ + void + ], "nonpayable">; + authorisations: TypedContractMethod<[ + arg0: BytesLike, + arg1: AddressLike, + arg2: AddressLike + ], [ + boolean + ], "view">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "supportsInterface"): TypedContractMethod<[interfaceID: BytesLike], [boolean], "view">; + getFunction(nameOrSignature: "setText"): TypedContractMethod<[ + node: BytesLike, + key: string, + value: string + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "interfaceImplementer"): TypedContractMethod<[ + node: BytesLike, + interfaceID: BytesLike + ], [ + string + ], "view">; + getFunction(nameOrSignature: "ABI"): TypedContractMethod<[ + node: BytesLike, + contentTypes: BigNumberish + ], [ + [bigint, string] + ], "view">; + getFunction(nameOrSignature: "setPubkey"): TypedContractMethod<[ + node: BytesLike, + x: BytesLike, + y: BytesLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "setContenthash"): TypedContractMethod<[ + node: BytesLike, + hash: BytesLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "addr(bytes32)"): TypedContractMethod<[node: BytesLike], [string], "view">; + getFunction(nameOrSignature: "addr(bytes32,uint256)"): TypedContractMethod<[ + node: BytesLike, + coinType: BigNumberish + ], [ + string + ], "view">; + getFunction(nameOrSignature: "setAuthorisation"): TypedContractMethod<[ + node: BytesLike, + target: AddressLike, + isAuthorised: boolean + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "text"): TypedContractMethod<[node: BytesLike, key: string], [string], "view">; + getFunction(nameOrSignature: "setABI"): TypedContractMethod<[ + node: BytesLike, + contentType: BigNumberish, + data: BytesLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "name"): TypedContractMethod<[node: BytesLike], [string], "view">; + getFunction(nameOrSignature: "setName"): TypedContractMethod<[node: BytesLike, name: string], [void], "nonpayable">; + getFunction(nameOrSignature: "setAddr(bytes32,uint256,bytes)"): TypedContractMethod<[ + node: BytesLike, + coinType: BigNumberish, + a: BytesLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "setAddr(bytes32,address)"): TypedContractMethod<[ + node: BytesLike, + a: AddressLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "contenthash"): TypedContractMethod<[node: BytesLike], [string], "view">; + getFunction(nameOrSignature: "pubkey"): TypedContractMethod<[ + node: BytesLike + ], [ + [string, string] & { + x: string; + y: string; + } + ], "view">; + getFunction(nameOrSignature: "setInterface"): TypedContractMethod<[ + node: BytesLike, + interfaceID: BytesLike, + implementer: AddressLike + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "authorisations"): TypedContractMethod<[ + arg0: BytesLike, + arg1: AddressLike, + arg2: AddressLike + ], [ + boolean + ], "view">; + getEvent(key: "AuthorisationChanged"): TypedContractEvent; + getEvent(key: "TextChanged"): TypedContractEvent; + getEvent(key: "PubkeyChanged"): TypedContractEvent; + getEvent(key: "NameChanged"): TypedContractEvent; + getEvent(key: "InterfaceChanged"): TypedContractEvent; + getEvent(key: "ContenthashChanged"): TypedContractEvent; + getEvent(key: "AddrChanged"): TypedContractEvent; + getEvent(key: "AddressChanged"): TypedContractEvent; + getEvent(key: "ABIChanged"): TypedContractEvent; + filters: { + "AuthorisationChanged(bytes32,address,address,bool)": TypedContractEvent; + AuthorisationChanged: TypedContractEvent; + "TextChanged(bytes32,string,string)": TypedContractEvent; + TextChanged: TypedContractEvent; + "PubkeyChanged(bytes32,bytes32,bytes32)": TypedContractEvent; + PubkeyChanged: TypedContractEvent; + "NameChanged(bytes32,string)": TypedContractEvent; + NameChanged: TypedContractEvent; + "InterfaceChanged(bytes32,bytes4,address)": TypedContractEvent; + InterfaceChanged: TypedContractEvent; + "ContenthashChanged(bytes32,bytes)": TypedContractEvent; + ContenthashChanged: TypedContractEvent; + "AddrChanged(bytes32,address)": TypedContractEvent; + AddrChanged: TypedContractEvent; + "AddressChanged(bytes32,uint256,bytes)": TypedContractEvent; + AddressChanged: TypedContractEvent; + "ABIChanged(bytes32,uint256)": TypedContractEvent; + ABIChanged: TypedContractEvent; + }; +} diff --git a/dist/typechain/ERC20.d.ts b/dist/typechain/ERC20.d.ts new file mode 100644 index 0000000..6e3ee80 --- /dev/null +++ b/dist/typechain/ERC20.d.ts @@ -0,0 +1,181 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, EventFragment, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedLogDescription, TypedListener, TypedContractMethod } from "./common"; +export interface ERC20Interface extends Interface { + getFunction(nameOrSignature: "totalSupply" | "_totalSupply" | "balanceOf" | "name" | "symbol" | "decimals" | "transfer" | "allowance" | "transferFrom" | "approve" | "nonces" | "permit"): FunctionFragment; + getEvent(nameOrSignatureOrTopic: "Approval" | "Transfer"): EventFragment; + encodeFunctionData(functionFragment: "totalSupply", values?: undefined): string; + encodeFunctionData(functionFragment: "_totalSupply", values?: undefined): string; + encodeFunctionData(functionFragment: "balanceOf", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "name", values?: undefined): string; + encodeFunctionData(functionFragment: "symbol", values?: undefined): string; + encodeFunctionData(functionFragment: "decimals", values?: undefined): string; + encodeFunctionData(functionFragment: "transfer", values: [AddressLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "allowance", values: [AddressLike, AddressLike]): string; + encodeFunctionData(functionFragment: "transferFrom", values: [AddressLike, AddressLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "approve", values: [AddressLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "nonces", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "permit", values: [ + AddressLike, + AddressLike, + BigNumberish, + BigNumberish, + BigNumberish, + BytesLike, + BytesLike + ]): string; + decodeFunctionResult(functionFragment: "totalSupply", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "_totalSupply", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "balanceOf", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "name", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "symbol", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "decimals", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "transfer", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "allowance", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "transferFrom", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "approve", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "nonces", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "permit", data: BytesLike): Result; +} +export declare namespace ApprovalEvent { + type InputTuple = [ + owner: AddressLike, + spender: AddressLike, + value: BigNumberish + ]; + type OutputTuple = [owner: string, spender: string, value: bigint]; + interface OutputObject { + owner: string; + spender: string; + value: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace TransferEvent { + type InputTuple = [ + from: AddressLike, + to: AddressLike, + value: BigNumberish + ]; + type OutputTuple = [from: string, to: string, value: bigint]; + interface OutputObject { + from: string; + to: string; + value: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export interface ERC20 extends BaseContract { + connect(runner?: ContractRunner | null): ERC20; + waitForDeployment(): Promise; + interface: ERC20Interface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + totalSupply: TypedContractMethod<[], [bigint], "view">; + _totalSupply: TypedContractMethod<[], [bigint], "view">; + balanceOf: TypedContractMethod<[who: AddressLike], [bigint], "view">; + name: TypedContractMethod<[], [string], "view">; + symbol: TypedContractMethod<[], [string], "view">; + decimals: TypedContractMethod<[], [bigint], "view">; + transfer: TypedContractMethod<[ + to: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + allowance: TypedContractMethod<[ + owner: AddressLike, + spender: AddressLike + ], [ + bigint + ], "view">; + transferFrom: TypedContractMethod<[ + from: AddressLike, + to: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + approve: TypedContractMethod<[ + spender: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + nonces: TypedContractMethod<[owner: AddressLike], [bigint], "view">; + permit: TypedContractMethod<[ + owner: AddressLike, + spender: AddressLike, + amount: BigNumberish, + deadline: BigNumberish, + v: BigNumberish, + r: BytesLike, + s: BytesLike + ], [ + void + ], "nonpayable">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "totalSupply"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "_totalSupply"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "balanceOf"): TypedContractMethod<[who: AddressLike], [bigint], "view">; + getFunction(nameOrSignature: "name"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "symbol"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "decimals"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "transfer"): TypedContractMethod<[ + to: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "allowance"): TypedContractMethod<[ + owner: AddressLike, + spender: AddressLike + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "transferFrom"): TypedContractMethod<[ + from: AddressLike, + to: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "approve"): TypedContractMethod<[ + spender: AddressLike, + value: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "nonces"): TypedContractMethod<[owner: AddressLike], [bigint], "view">; + getFunction(nameOrSignature: "permit"): TypedContractMethod<[ + owner: AddressLike, + spender: AddressLike, + amount: BigNumberish, + deadline: BigNumberish, + v: BigNumberish, + r: BytesLike, + s: BytesLike + ], [ + void + ], "nonpayable">; + getEvent(key: "Approval"): TypedContractEvent; + getEvent(key: "Transfer"): TypedContractEvent; + filters: { + "Approval(address,address,uint256)": TypedContractEvent; + Approval: TypedContractEvent; + "Transfer(address,address,uint256)": TypedContractEvent; + Transfer: TypedContractEvent; + }; +} diff --git a/dist/typechain/GasPriceOracle.d.ts b/dist/typechain/GasPriceOracle.d.ts new file mode 100644 index 0000000..0ff65c8 --- /dev/null +++ b/dist/typechain/GasPriceOracle.d.ts @@ -0,0 +1,101 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedListener, TypedContractMethod } from "./common"; +export interface GasPriceOracleInterface extends Interface { + getFunction(nameOrSignature: "GAS_UNIT" | "changeDerivationThresold" | "changeGasUnit" | "changeHeartbeat" | "changeOwnership" | "derivationThresold" | "gasPrice" | "heartbeat" | "maxFeePerGas" | "maxPriorityFeePerGas" | "owner" | "pastGasPrice" | "setGasPrice" | "timestamp"): FunctionFragment; + encodeFunctionData(functionFragment: "GAS_UNIT", values?: undefined): string; + encodeFunctionData(functionFragment: "changeDerivationThresold", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "changeGasUnit", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "changeHeartbeat", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "changeOwnership", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "derivationThresold", values?: undefined): string; + encodeFunctionData(functionFragment: "gasPrice", values?: undefined): string; + encodeFunctionData(functionFragment: "heartbeat", values?: undefined): string; + encodeFunctionData(functionFragment: "maxFeePerGas", values?: undefined): string; + encodeFunctionData(functionFragment: "maxPriorityFeePerGas", values?: undefined): string; + encodeFunctionData(functionFragment: "owner", values?: undefined): string; + encodeFunctionData(functionFragment: "pastGasPrice", values?: undefined): string; + encodeFunctionData(functionFragment: "setGasPrice", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "timestamp", values?: undefined): string; + decodeFunctionResult(functionFragment: "GAS_UNIT", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "changeDerivationThresold", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "changeGasUnit", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "changeHeartbeat", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "changeOwnership", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "derivationThresold", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "gasPrice", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "heartbeat", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "maxFeePerGas", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "maxPriorityFeePerGas", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "owner", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "pastGasPrice", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setGasPrice", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "timestamp", data: BytesLike): Result; +} +export interface GasPriceOracle extends BaseContract { + connect(runner?: ContractRunner | null): GasPriceOracle; + waitForDeployment(): Promise; + interface: GasPriceOracleInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + GAS_UNIT: TypedContractMethod<[], [bigint], "view">; + changeDerivationThresold: TypedContractMethod<[ + _derivationThresold: BigNumberish + ], [ + void + ], "nonpayable">; + changeGasUnit: TypedContractMethod<[ + _gasUnit: BigNumberish + ], [ + void + ], "nonpayable">; + changeHeartbeat: TypedContractMethod<[ + _heartbeat: BigNumberish + ], [ + void + ], "nonpayable">; + changeOwnership: TypedContractMethod<[ + _owner: AddressLike + ], [ + void + ], "nonpayable">; + derivationThresold: TypedContractMethod<[], [bigint], "view">; + gasPrice: TypedContractMethod<[], [bigint], "view">; + heartbeat: TypedContractMethod<[], [bigint], "view">; + maxFeePerGas: TypedContractMethod<[], [bigint], "view">; + maxPriorityFeePerGas: TypedContractMethod<[], [bigint], "view">; + owner: TypedContractMethod<[], [string], "view">; + pastGasPrice: TypedContractMethod<[], [bigint], "view">; + setGasPrice: TypedContractMethod<[ + _gasPrice: BigNumberish + ], [ + void + ], "nonpayable">; + timestamp: TypedContractMethod<[], [bigint], "view">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "GAS_UNIT"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "changeDerivationThresold"): TypedContractMethod<[ + _derivationThresold: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "changeGasUnit"): TypedContractMethod<[_gasUnit: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "changeHeartbeat"): TypedContractMethod<[_heartbeat: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "changeOwnership"): TypedContractMethod<[_owner: AddressLike], [void], "nonpayable">; + getFunction(nameOrSignature: "derivationThresold"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "gasPrice"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "heartbeat"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "maxFeePerGas"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "maxPriorityFeePerGas"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "owner"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "pastGasPrice"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "setGasPrice"): TypedContractMethod<[_gasPrice: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "timestamp"): TypedContractMethod<[], [bigint], "view">; + filters: {}; +} diff --git a/dist/typechain/Multicall.d.ts b/dist/typechain/Multicall.d.ts new file mode 100644 index 0000000..e1bfd18 --- /dev/null +++ b/dist/typechain/Multicall.d.ts @@ -0,0 +1,228 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedListener, TypedContractMethod } from "./common"; +export declare namespace Multicall3 { + type CallStruct = { + target: AddressLike; + callData: BytesLike; + }; + type CallStructOutput = [target: string, callData: string] & { + target: string; + callData: string; + }; + type Call3Struct = { + target: AddressLike; + allowFailure: boolean; + callData: BytesLike; + }; + type Call3StructOutput = [ + target: string, + allowFailure: boolean, + callData: string + ] & { + target: string; + allowFailure: boolean; + callData: string; + }; + type ResultStruct = { + success: boolean; + returnData: BytesLike; + }; + type ResultStructOutput = [success: boolean, returnData: string] & { + success: boolean; + returnData: string; + }; + type Call3ValueStruct = { + target: AddressLike; + allowFailure: boolean; + value: BigNumberish; + callData: BytesLike; + }; + type Call3ValueStructOutput = [ + target: string, + allowFailure: boolean, + value: bigint, + callData: string + ] & { + target: string; + allowFailure: boolean; + value: bigint; + callData: string; + }; +} +export interface MulticallInterface extends Interface { + getFunction(nameOrSignature: "aggregate" | "aggregate3" | "aggregate3Value" | "blockAndAggregate" | "getBasefee" | "getBlockHash" | "getBlockNumber" | "getChainId" | "getCurrentBlockCoinbase" | "getCurrentBlockDifficulty" | "getCurrentBlockGasLimit" | "getCurrentBlockTimestamp" | "getEthBalance" | "getLastBlockHash" | "tryAggregate" | "tryBlockAndAggregate"): FunctionFragment; + encodeFunctionData(functionFragment: "aggregate", values: [Multicall3.CallStruct[]]): string; + encodeFunctionData(functionFragment: "aggregate3", values: [Multicall3.Call3Struct[]]): string; + encodeFunctionData(functionFragment: "aggregate3Value", values: [Multicall3.Call3ValueStruct[]]): string; + encodeFunctionData(functionFragment: "blockAndAggregate", values: [Multicall3.CallStruct[]]): string; + encodeFunctionData(functionFragment: "getBasefee", values?: undefined): string; + encodeFunctionData(functionFragment: "getBlockHash", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "getBlockNumber", values?: undefined): string; + encodeFunctionData(functionFragment: "getChainId", values?: undefined): string; + encodeFunctionData(functionFragment: "getCurrentBlockCoinbase", values?: undefined): string; + encodeFunctionData(functionFragment: "getCurrentBlockDifficulty", values?: undefined): string; + encodeFunctionData(functionFragment: "getCurrentBlockGasLimit", values?: undefined): string; + encodeFunctionData(functionFragment: "getCurrentBlockTimestamp", values?: undefined): string; + encodeFunctionData(functionFragment: "getEthBalance", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "getLastBlockHash", values?: undefined): string; + encodeFunctionData(functionFragment: "tryAggregate", values: [boolean, Multicall3.CallStruct[]]): string; + encodeFunctionData(functionFragment: "tryBlockAndAggregate", values: [boolean, Multicall3.CallStruct[]]): string; + decodeFunctionResult(functionFragment: "aggregate", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "aggregate3", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "aggregate3Value", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "blockAndAggregate", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getBasefee", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getBlockHash", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getBlockNumber", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getChainId", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getCurrentBlockCoinbase", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getCurrentBlockDifficulty", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getCurrentBlockGasLimit", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getCurrentBlockTimestamp", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getEthBalance", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getLastBlockHash", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "tryAggregate", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "tryBlockAndAggregate", data: BytesLike): Result; +} +export interface Multicall extends BaseContract { + connect(runner?: ContractRunner | null): Multicall; + waitForDeployment(): Promise; + interface: MulticallInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + aggregate: TypedContractMethod<[ + calls: Multicall3.CallStruct[] + ], [ + [bigint, string[]] & { + blockNumber: bigint; + returnData: string[]; + } + ], "payable">; + aggregate3: TypedContractMethod<[ + calls: Multicall3.Call3Struct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + aggregate3Value: TypedContractMethod<[ + calls: Multicall3.Call3ValueStruct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + blockAndAggregate: TypedContractMethod<[ + calls: Multicall3.CallStruct[] + ], [ + [ + bigint, + string, + Multicall3.ResultStructOutput[] + ] & { + blockNumber: bigint; + blockHash: string; + returnData: Multicall3.ResultStructOutput[]; + } + ], "payable">; + getBasefee: TypedContractMethod<[], [bigint], "view">; + getBlockHash: TypedContractMethod<[ + blockNumber: BigNumberish + ], [ + string + ], "view">; + getBlockNumber: TypedContractMethod<[], [bigint], "view">; + getChainId: TypedContractMethod<[], [bigint], "view">; + getCurrentBlockCoinbase: TypedContractMethod<[], [string], "view">; + getCurrentBlockDifficulty: TypedContractMethod<[], [bigint], "view">; + getCurrentBlockGasLimit: TypedContractMethod<[], [bigint], "view">; + getCurrentBlockTimestamp: TypedContractMethod<[], [bigint], "view">; + getEthBalance: TypedContractMethod<[addr: AddressLike], [bigint], "view">; + getLastBlockHash: TypedContractMethod<[], [string], "view">; + tryAggregate: TypedContractMethod<[ + requireSuccess: boolean, + calls: Multicall3.CallStruct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + tryBlockAndAggregate: TypedContractMethod<[ + requireSuccess: boolean, + calls: Multicall3.CallStruct[] + ], [ + [ + bigint, + string, + Multicall3.ResultStructOutput[] + ] & { + blockNumber: bigint; + blockHash: string; + returnData: Multicall3.ResultStructOutput[]; + } + ], "payable">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "aggregate"): TypedContractMethod<[ + calls: Multicall3.CallStruct[] + ], [ + [bigint, string[]] & { + blockNumber: bigint; + returnData: string[]; + } + ], "payable">; + getFunction(nameOrSignature: "aggregate3"): TypedContractMethod<[ + calls: Multicall3.Call3Struct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + getFunction(nameOrSignature: "aggregate3Value"): TypedContractMethod<[ + calls: Multicall3.Call3ValueStruct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + getFunction(nameOrSignature: "blockAndAggregate"): TypedContractMethod<[ + calls: Multicall3.CallStruct[] + ], [ + [ + bigint, + string, + Multicall3.ResultStructOutput[] + ] & { + blockNumber: bigint; + blockHash: string; + returnData: Multicall3.ResultStructOutput[]; + } + ], "payable">; + getFunction(nameOrSignature: "getBasefee"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getBlockHash"): TypedContractMethod<[blockNumber: BigNumberish], [string], "view">; + getFunction(nameOrSignature: "getBlockNumber"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getChainId"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getCurrentBlockCoinbase"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "getCurrentBlockDifficulty"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getCurrentBlockGasLimit"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getCurrentBlockTimestamp"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getEthBalance"): TypedContractMethod<[addr: AddressLike], [bigint], "view">; + getFunction(nameOrSignature: "getLastBlockHash"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "tryAggregate"): TypedContractMethod<[ + requireSuccess: boolean, + calls: Multicall3.CallStruct[] + ], [ + Multicall3.ResultStructOutput[] + ], "payable">; + getFunction(nameOrSignature: "tryBlockAndAggregate"): TypedContractMethod<[ + requireSuccess: boolean, + calls: Multicall3.CallStruct[] + ], [ + [ + bigint, + string, + Multicall3.ResultStructOutput[] + ] & { + blockNumber: bigint; + blockHash: string; + returnData: Multicall3.ResultStructOutput[]; + } + ], "payable">; + filters: {}; +} diff --git a/dist/typechain/OffchainOracle.d.ts b/dist/typechain/OffchainOracle.d.ts new file mode 100644 index 0000000..853f317 --- /dev/null +++ b/dist/typechain/OffchainOracle.d.ts @@ -0,0 +1,304 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, EventFragment, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedLogDescription, TypedListener, TypedContractMethod } from "./common"; +export interface OffchainOracleInterface extends Interface { + getFunction(nameOrSignature: "addConnector" | "addOracle" | "connectors" | "getRate" | "getRateToEth" | "getRateToEthWithCustomConnectors" | "getRateToEthWithThreshold" | "getRateWithCustomConnectors" | "getRateWithThreshold" | "multiWrapper" | "oracles" | "owner" | "removeConnector" | "removeOracle" | "renounceOwnership" | "setMultiWrapper" | "transferOwnership"): FunctionFragment; + getEvent(nameOrSignatureOrTopic: "ConnectorAdded" | "ConnectorRemoved" | "MultiWrapperUpdated" | "OracleAdded" | "OracleRemoved" | "OwnershipTransferred"): EventFragment; + encodeFunctionData(functionFragment: "addConnector", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "addOracle", values: [AddressLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "connectors", values?: undefined): string; + encodeFunctionData(functionFragment: "getRate", values: [AddressLike, AddressLike, boolean]): string; + encodeFunctionData(functionFragment: "getRateToEth", values: [AddressLike, boolean]): string; + encodeFunctionData(functionFragment: "getRateToEthWithCustomConnectors", values: [AddressLike, boolean, AddressLike[], BigNumberish]): string; + encodeFunctionData(functionFragment: "getRateToEthWithThreshold", values: [AddressLike, boolean, BigNumberish]): string; + encodeFunctionData(functionFragment: "getRateWithCustomConnectors", values: [AddressLike, AddressLike, boolean, AddressLike[], BigNumberish]): string; + encodeFunctionData(functionFragment: "getRateWithThreshold", values: [AddressLike, AddressLike, boolean, BigNumberish]): string; + encodeFunctionData(functionFragment: "multiWrapper", values?: undefined): string; + encodeFunctionData(functionFragment: "oracles", values?: undefined): string; + encodeFunctionData(functionFragment: "owner", values?: undefined): string; + encodeFunctionData(functionFragment: "removeConnector", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "removeOracle", values: [AddressLike, BigNumberish]): string; + encodeFunctionData(functionFragment: "renounceOwnership", values?: undefined): string; + encodeFunctionData(functionFragment: "setMultiWrapper", values: [AddressLike]): string; + encodeFunctionData(functionFragment: "transferOwnership", values: [AddressLike]): string; + decodeFunctionResult(functionFragment: "addConnector", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "addOracle", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "connectors", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRate", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRateToEth", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRateToEthWithCustomConnectors", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRateToEthWithThreshold", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRateWithCustomConnectors", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getRateWithThreshold", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "multiWrapper", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "oracles", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "owner", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "removeConnector", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "removeOracle", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "renounceOwnership", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setMultiWrapper", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "transferOwnership", data: BytesLike): Result; +} +export declare namespace ConnectorAddedEvent { + type InputTuple = [connector: AddressLike]; + type OutputTuple = [connector: string]; + interface OutputObject { + connector: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace ConnectorRemovedEvent { + type InputTuple = [connector: AddressLike]; + type OutputTuple = [connector: string]; + interface OutputObject { + connector: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace MultiWrapperUpdatedEvent { + type InputTuple = [multiWrapper: AddressLike]; + type OutputTuple = [multiWrapper: string]; + interface OutputObject { + multiWrapper: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace OracleAddedEvent { + type InputTuple = [oracle: AddressLike, oracleType: BigNumberish]; + type OutputTuple = [oracle: string, oracleType: bigint]; + interface OutputObject { + oracle: string; + oracleType: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace OracleRemovedEvent { + type InputTuple = [oracle: AddressLike, oracleType: BigNumberish]; + type OutputTuple = [oracle: string, oracleType: bigint]; + interface OutputObject { + oracle: string; + oracleType: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace OwnershipTransferredEvent { + type InputTuple = [previousOwner: AddressLike, newOwner: AddressLike]; + type OutputTuple = [previousOwner: string, newOwner: string]; + interface OutputObject { + previousOwner: string; + newOwner: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export interface OffchainOracle extends BaseContract { + connect(runner?: ContractRunner | null): OffchainOracle; + waitForDeployment(): Promise; + interface: OffchainOracleInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + addConnector: TypedContractMethod<[ + connector: AddressLike + ], [ + void + ], "nonpayable">; + addOracle: TypedContractMethod<[ + oracle: AddressLike, + oracleKind: BigNumberish + ], [ + void + ], "nonpayable">; + connectors: TypedContractMethod<[], [string[]], "view">; + getRate: TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean + ], [ + bigint + ], "view">; + getRateToEth: TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean + ], [ + bigint + ], "view">; + getRateToEthWithCustomConnectors: TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean, + customConnectors: AddressLike[], + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getRateToEthWithThreshold: TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean, + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getRateWithCustomConnectors: TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean, + customConnectors: AddressLike[], + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getRateWithThreshold: TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean, + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + multiWrapper: TypedContractMethod<[], [string], "view">; + oracles: TypedContractMethod<[ + ], [ + [string[], bigint[]] & { + allOracles: string[]; + oracleTypes: bigint[]; + } + ], "view">; + owner: TypedContractMethod<[], [string], "view">; + removeConnector: TypedContractMethod<[ + connector: AddressLike + ], [ + void + ], "nonpayable">; + removeOracle: TypedContractMethod<[ + oracle: AddressLike, + oracleKind: BigNumberish + ], [ + void + ], "nonpayable">; + renounceOwnership: TypedContractMethod<[], [void], "nonpayable">; + setMultiWrapper: TypedContractMethod<[ + _multiWrapper: AddressLike + ], [ + void + ], "nonpayable">; + transferOwnership: TypedContractMethod<[ + newOwner: AddressLike + ], [ + void + ], "nonpayable">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "addConnector"): TypedContractMethod<[connector: AddressLike], [void], "nonpayable">; + getFunction(nameOrSignature: "addOracle"): TypedContractMethod<[ + oracle: AddressLike, + oracleKind: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "connectors"): TypedContractMethod<[], [string[]], "view">; + getFunction(nameOrSignature: "getRate"): TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "getRateToEth"): TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "getRateToEthWithCustomConnectors"): TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean, + customConnectors: AddressLike[], + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "getRateToEthWithThreshold"): TypedContractMethod<[ + srcToken: AddressLike, + useSrcWrappers: boolean, + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "getRateWithCustomConnectors"): TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean, + customConnectors: AddressLike[], + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "getRateWithThreshold"): TypedContractMethod<[ + srcToken: AddressLike, + dstToken: AddressLike, + useWrappers: boolean, + thresholdFilter: BigNumberish + ], [ + bigint + ], "view">; + getFunction(nameOrSignature: "multiWrapper"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "oracles"): TypedContractMethod<[ + ], [ + [string[], bigint[]] & { + allOracles: string[]; + oracleTypes: bigint[]; + } + ], "view">; + getFunction(nameOrSignature: "owner"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "removeConnector"): TypedContractMethod<[connector: AddressLike], [void], "nonpayable">; + getFunction(nameOrSignature: "removeOracle"): TypedContractMethod<[ + oracle: AddressLike, + oracleKind: BigNumberish + ], [ + void + ], "nonpayable">; + getFunction(nameOrSignature: "renounceOwnership"): TypedContractMethod<[], [void], "nonpayable">; + getFunction(nameOrSignature: "setMultiWrapper"): TypedContractMethod<[_multiWrapper: AddressLike], [void], "nonpayable">; + getFunction(nameOrSignature: "transferOwnership"): TypedContractMethod<[newOwner: AddressLike], [void], "nonpayable">; + getEvent(key: "ConnectorAdded"): TypedContractEvent; + getEvent(key: "ConnectorRemoved"): TypedContractEvent; + getEvent(key: "MultiWrapperUpdated"): TypedContractEvent; + getEvent(key: "OracleAdded"): TypedContractEvent; + getEvent(key: "OracleRemoved"): TypedContractEvent; + getEvent(key: "OwnershipTransferred"): TypedContractEvent; + filters: { + "ConnectorAdded(address)": TypedContractEvent; + ConnectorAdded: TypedContractEvent; + "ConnectorRemoved(address)": TypedContractEvent; + ConnectorRemoved: TypedContractEvent; + "MultiWrapperUpdated(address)": TypedContractEvent; + MultiWrapperUpdated: TypedContractEvent; + "OracleAdded(address,uint8)": TypedContractEvent; + OracleAdded: TypedContractEvent; + "OracleRemoved(address,uint8)": TypedContractEvent; + OracleRemoved: TypedContractEvent; + "OwnershipTransferred(address,address)": TypedContractEvent; + OwnershipTransferred: TypedContractEvent; + }; +} diff --git a/dist/typechain/OvmGasPriceOracle.d.ts b/dist/typechain/OvmGasPriceOracle.d.ts new file mode 100644 index 0000000..b67f111 --- /dev/null +++ b/dist/typechain/OvmGasPriceOracle.d.ts @@ -0,0 +1,188 @@ +import type { BaseContract, BigNumberish, BytesLike, FunctionFragment, Result, Interface, EventFragment, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedLogDescription, TypedListener, TypedContractMethod } from "./common"; +export interface OvmGasPriceOracleInterface extends Interface { + getFunction(nameOrSignature: "decimals" | "gasPrice" | "getL1Fee" | "getL1GasUsed" | "l1BaseFee" | "overhead" | "owner" | "renounceOwnership" | "scalar" | "setDecimals" | "setGasPrice" | "setL1BaseFee" | "setOverhead" | "setScalar" | "transferOwnership"): FunctionFragment; + getEvent(nameOrSignatureOrTopic: "DecimalsUpdated" | "GasPriceUpdated" | "L1BaseFeeUpdated" | "OverheadUpdated" | "OwnershipTransferred" | "ScalarUpdated"): EventFragment; + encodeFunctionData(functionFragment: "decimals", values?: undefined): string; + encodeFunctionData(functionFragment: "gasPrice", values?: undefined): string; + encodeFunctionData(functionFragment: "getL1Fee", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "getL1GasUsed", values: [BytesLike]): string; + encodeFunctionData(functionFragment: "l1BaseFee", values?: undefined): string; + encodeFunctionData(functionFragment: "overhead", values?: undefined): string; + encodeFunctionData(functionFragment: "owner", values?: undefined): string; + encodeFunctionData(functionFragment: "renounceOwnership", values?: undefined): string; + encodeFunctionData(functionFragment: "scalar", values?: undefined): string; + encodeFunctionData(functionFragment: "setDecimals", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "setGasPrice", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "setL1BaseFee", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "setOverhead", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "setScalar", values: [BigNumberish]): string; + encodeFunctionData(functionFragment: "transferOwnership", values: [AddressLike]): string; + decodeFunctionResult(functionFragment: "decimals", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "gasPrice", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getL1Fee", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "getL1GasUsed", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "l1BaseFee", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "overhead", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "owner", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "renounceOwnership", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "scalar", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setDecimals", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setGasPrice", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setL1BaseFee", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setOverhead", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "setScalar", data: BytesLike): Result; + decodeFunctionResult(functionFragment: "transferOwnership", data: BytesLike): Result; +} +export declare namespace DecimalsUpdatedEvent { + type InputTuple = [arg0: BigNumberish]; + type OutputTuple = [arg0: bigint]; + interface OutputObject { + arg0: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace GasPriceUpdatedEvent { + type InputTuple = [arg0: BigNumberish]; + type OutputTuple = [arg0: bigint]; + interface OutputObject { + arg0: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace L1BaseFeeUpdatedEvent { + type InputTuple = [arg0: BigNumberish]; + type OutputTuple = [arg0: bigint]; + interface OutputObject { + arg0: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace OverheadUpdatedEvent { + type InputTuple = [arg0: BigNumberish]; + type OutputTuple = [arg0: bigint]; + interface OutputObject { + arg0: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace OwnershipTransferredEvent { + type InputTuple = [previousOwner: AddressLike, newOwner: AddressLike]; + type OutputTuple = [previousOwner: string, newOwner: string]; + interface OutputObject { + previousOwner: string; + newOwner: string; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export declare namespace ScalarUpdatedEvent { + type InputTuple = [arg0: BigNumberish]; + type OutputTuple = [arg0: bigint]; + interface OutputObject { + arg0: bigint; + } + type Event = TypedContractEvent; + type Filter = TypedDeferredTopicFilter; + type Log = TypedEventLog; + type LogDescription = TypedLogDescription; +} +export interface OvmGasPriceOracle extends BaseContract { + connect(runner?: ContractRunner | null): OvmGasPriceOracle; + waitForDeployment(): Promise; + interface: OvmGasPriceOracleInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + decimals: TypedContractMethod<[], [bigint], "view">; + gasPrice: TypedContractMethod<[], [bigint], "view">; + getL1Fee: TypedContractMethod<[_data: BytesLike], [bigint], "view">; + getL1GasUsed: TypedContractMethod<[_data: BytesLike], [bigint], "view">; + l1BaseFee: TypedContractMethod<[], [bigint], "view">; + overhead: TypedContractMethod<[], [bigint], "view">; + owner: TypedContractMethod<[], [string], "view">; + renounceOwnership: TypedContractMethod<[], [void], "nonpayable">; + scalar: TypedContractMethod<[], [bigint], "view">; + setDecimals: TypedContractMethod<[ + _decimals: BigNumberish + ], [ + void + ], "nonpayable">; + setGasPrice: TypedContractMethod<[ + _gasPrice: BigNumberish + ], [ + void + ], "nonpayable">; + setL1BaseFee: TypedContractMethod<[ + _baseFee: BigNumberish + ], [ + void + ], "nonpayable">; + setOverhead: TypedContractMethod<[ + _overhead: BigNumberish + ], [ + void + ], "nonpayable">; + setScalar: TypedContractMethod<[_scalar: BigNumberish], [void], "nonpayable">; + transferOwnership: TypedContractMethod<[ + newOwner: AddressLike + ], [ + void + ], "nonpayable">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "decimals"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "gasPrice"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "getL1Fee"): TypedContractMethod<[_data: BytesLike], [bigint], "view">; + getFunction(nameOrSignature: "getL1GasUsed"): TypedContractMethod<[_data: BytesLike], [bigint], "view">; + getFunction(nameOrSignature: "l1BaseFee"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "overhead"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "owner"): TypedContractMethod<[], [string], "view">; + getFunction(nameOrSignature: "renounceOwnership"): TypedContractMethod<[], [void], "nonpayable">; + getFunction(nameOrSignature: "scalar"): TypedContractMethod<[], [bigint], "view">; + getFunction(nameOrSignature: "setDecimals"): TypedContractMethod<[_decimals: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "setGasPrice"): TypedContractMethod<[_gasPrice: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "setL1BaseFee"): TypedContractMethod<[_baseFee: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "setOverhead"): TypedContractMethod<[_overhead: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "setScalar"): TypedContractMethod<[_scalar: BigNumberish], [void], "nonpayable">; + getFunction(nameOrSignature: "transferOwnership"): TypedContractMethod<[newOwner: AddressLike], [void], "nonpayable">; + getEvent(key: "DecimalsUpdated"): TypedContractEvent; + getEvent(key: "GasPriceUpdated"): TypedContractEvent; + getEvent(key: "L1BaseFeeUpdated"): TypedContractEvent; + getEvent(key: "OverheadUpdated"): TypedContractEvent; + getEvent(key: "OwnershipTransferred"): TypedContractEvent; + getEvent(key: "ScalarUpdated"): TypedContractEvent; + filters: { + "DecimalsUpdated(uint256)": TypedContractEvent; + DecimalsUpdated: TypedContractEvent; + "GasPriceUpdated(uint256)": TypedContractEvent; + GasPriceUpdated: TypedContractEvent; + "L1BaseFeeUpdated(uint256)": TypedContractEvent; + L1BaseFeeUpdated: TypedContractEvent; + "OverheadUpdated(uint256)": TypedContractEvent; + OverheadUpdated: TypedContractEvent; + "OwnershipTransferred(address,address)": TypedContractEvent; + OwnershipTransferred: TypedContractEvent; + "ScalarUpdated(uint256)": TypedContractEvent; + ScalarUpdated: TypedContractEvent; + }; +} diff --git a/dist/typechain/ReverseRecords.d.ts b/dist/typechain/ReverseRecords.d.ts new file mode 100644 index 0000000..b26cfb5 --- /dev/null +++ b/dist/typechain/ReverseRecords.d.ts @@ -0,0 +1,25 @@ +import type { BaseContract, BytesLike, FunctionFragment, Result, Interface, AddressLike, ContractRunner, ContractMethod, Listener } from "ethers"; +import type { TypedContractEvent, TypedDeferredTopicFilter, TypedEventLog, TypedListener, TypedContractMethod } from "./common"; +export interface ReverseRecordsInterface extends Interface { + getFunction(nameOrSignature: "getNames"): FunctionFragment; + encodeFunctionData(functionFragment: "getNames", values: [AddressLike[]]): string; + decodeFunctionResult(functionFragment: "getNames", data: BytesLike): Result; +} +export interface ReverseRecords extends BaseContract { + connect(runner?: ContractRunner | null): ReverseRecords; + waitForDeployment(): Promise; + interface: ReverseRecordsInterface; + queryFilter(event: TCEvent, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + queryFilter(filter: TypedDeferredTopicFilter, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined): Promise>>; + on(event: TCEvent, listener: TypedListener): Promise; + on(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + once(event: TCEvent, listener: TypedListener): Promise; + once(filter: TypedDeferredTopicFilter, listener: TypedListener): Promise; + listeners(event: TCEvent): Promise>>; + listeners(eventName?: string): Promise>; + removeAllListeners(event?: TCEvent): Promise; + getNames: TypedContractMethod<[addresses: AddressLike[]], [string[]], "view">; + getFunction(key: string | FunctionFragment): T; + getFunction(nameOrSignature: "getNames"): TypedContractMethod<[addresses: AddressLike[]], [string[]], "view">; + filters: {}; +} diff --git a/dist/typechain/common.d.ts b/dist/typechain/common.d.ts new file mode 100644 index 0000000..d6c302a --- /dev/null +++ b/dist/typechain/common.d.ts @@ -0,0 +1,50 @@ +import type { FunctionFragment, Typed, EventFragment, ContractTransaction, ContractTransactionResponse, DeferredTopicFilter, EventLog, TransactionRequest, LogDescription } from "ethers"; +export interface TypedDeferredTopicFilter<_TCEvent extends TypedContractEvent> extends DeferredTopicFilter { +} +export interface TypedContractEvent = any, OutputTuple extends Array = any, OutputObject = any> { + (...args: Partial): TypedDeferredTopicFilter>; + name: string; + fragment: EventFragment; + getFragment(...args: Partial): EventFragment; +} +type __TypechainAOutputTuple = T extends TypedContractEvent ? W : never; +type __TypechainOutputObject = T extends TypedContractEvent ? V : never; +export interface TypedEventLog extends Omit { + args: __TypechainAOutputTuple & __TypechainOutputObject; +} +export interface TypedLogDescription extends Omit { + args: __TypechainAOutputTuple & __TypechainOutputObject; +} +export type TypedListener = (...listenerArg: [ + ...__TypechainAOutputTuple, + TypedEventLog, + ...undefined[] +]) => void; +export type MinEthersFactory = { + deploy(...a: ARGS[]): Promise; +}; +export type GetContractTypeFromFactory = F extends MinEthersFactory ? C : never; +export type GetARGsTypeFromFactory = F extends MinEthersFactory ? Parameters : never; +export type StateMutability = "nonpayable" | "payable" | "view"; +export type BaseOverrides = Omit; +export type NonPayableOverrides = Omit; +export type PayableOverrides = Omit; +export type ViewOverrides = Omit; +export type Overrides = S extends "nonpayable" ? NonPayableOverrides : S extends "payable" ? PayableOverrides : ViewOverrides; +export type PostfixOverrides, S extends StateMutability> = A | [...A, Overrides]; +export type ContractMethodArgs, S extends StateMutability> = PostfixOverrides<{ + [I in keyof A]-?: A[I] | Typed; +}, S>; +export type DefaultReturnType = R extends Array ? R[0] : R; +export interface TypedContractMethod = Array, R = any, S extends StateMutability = "payable"> { + (...args: ContractMethodArgs): S extends "view" ? Promise> : Promise; + name: string; + fragment: FunctionFragment; + getFragment(...args: ContractMethodArgs): FunctionFragment; + populateTransaction(...args: ContractMethodArgs): Promise; + staticCall(...args: ContractMethodArgs): Promise>; + send(...args: ContractMethodArgs): Promise; + estimateGas(...args: ContractMethodArgs): Promise; + staticCallResult(...args: ContractMethodArgs): Promise; +} +export {}; diff --git a/dist/typechain/factories/ENS__factory.d.ts b/dist/typechain/factories/ENS__factory.d.ts new file mode 100644 index 0000000..7a6db54 --- /dev/null +++ b/dist/typechain/factories/ENS__factory.d.ts @@ -0,0 +1,541 @@ +import { type ContractRunner } from "ethers"; +import type { ENS, ENSInterface } from "../ENS"; +export declare class ENS__factory { + static readonly abi: readonly [{ + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "supportsInterface"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly payable: false; + readonly stateMutability: "pure"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }, { + readonly internalType: "string"; + readonly name: "value"; + readonly type: "string"; + }]; + readonly name: "setText"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }]; + readonly name: "interfaceImplementer"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "contentTypes"; + readonly type: "uint256"; + }]; + readonly name: "ABI"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly name: "setPubkey"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes"; + readonly name: "hash"; + readonly type: "bytes"; + }]; + readonly name: "setContenthash"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "isAuthorised"; + readonly type: "bool"; + }]; + readonly name: "setAuthorisation"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "text"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "contentType"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: "data"; + readonly type: "bytes"; + }]; + readonly name: "setABI"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "name"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "string"; + readonly name: "name"; + readonly type: "string"; + }]; + readonly name: "setName"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: "a"; + readonly type: "bytes"; + }]; + readonly name: "setAddr"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "contenthash"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }]; + readonly name: "pubkey"; + readonly outputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "address"; + readonly name: "a"; + readonly type: "address"; + }]; + readonly name: "setAddr"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }, { + readonly internalType: "address"; + readonly name: "implementer"; + readonly type: "address"; + }]; + readonly name: "setInterface"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }]; + readonly name: "addr"; + readonly outputs: readonly [{ + readonly internalType: "bytes"; + readonly name: ""; + readonly type: "bytes"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: ""; + readonly type: "bytes32"; + }, { + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly name: "authorisations"; + readonly outputs: readonly [{ + readonly internalType: "bool"; + readonly name: ""; + readonly type: "bool"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract ENS"; + readonly name: "_ens"; + readonly type: "address"; + }]; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "constructor"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "bool"; + readonly name: "isAuthorised"; + readonly type: "bool"; + }]; + readonly name: "AuthorisationChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "indexedKey"; + readonly type: "string"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "key"; + readonly type: "string"; + }]; + readonly name: "TextChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "x"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes32"; + readonly name: "y"; + readonly type: "bytes32"; + }]; + readonly name: "PubkeyChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "string"; + readonly name: "name"; + readonly type: "string"; + }]; + readonly name: "NameChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "bytes4"; + readonly name: "interfaceID"; + readonly type: "bytes4"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "implementer"; + readonly type: "address"; + }]; + readonly name: "InterfaceChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "hash"; + readonly type: "bytes"; + }]; + readonly name: "ContenthashChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "address"; + readonly name: "a"; + readonly type: "address"; + }]; + readonly name: "AddrChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: "coinType"; + readonly type: "uint256"; + }, { + readonly indexed: false; + readonly internalType: "bytes"; + readonly name: "newAddress"; + readonly type: "bytes"; + }]; + readonly name: "AddressChanged"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "bytes32"; + readonly name: "node"; + readonly type: "bytes32"; + }, { + readonly indexed: true; + readonly internalType: "uint256"; + readonly name: "contentType"; + readonly type: "uint256"; + }]; + readonly name: "ABIChanged"; + readonly type: "event"; + }]; + static createInterface(): ENSInterface; + static connect(address: string, runner?: ContractRunner | null): ENS; +} diff --git a/dist/typechain/factories/ERC20__factory.d.ts b/dist/typechain/factories/ERC20__factory.d.ts new file mode 100644 index 0000000..218af25 --- /dev/null +++ b/dist/typechain/factories/ERC20__factory.d.ts @@ -0,0 +1,243 @@ +import { type ContractRunner } from "ethers"; +import type { ERC20, ERC20Interface } from "../ERC20"; +export declare class ERC20__factory { + static readonly abi: readonly [{ + readonly constant: true; + readonly inputs: readonly []; + readonly name: "totalSupply"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly []; + readonly name: "_totalSupply"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "who"; + readonly type: "address"; + }]; + readonly name: "balanceOf"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly []; + readonly name: "name"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly []; + readonly name: "symbol"; + readonly outputs: readonly [{ + readonly internalType: "string"; + readonly name: ""; + readonly type: "string"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: true; + readonly inputs: readonly []; + readonly name: "decimals"; + readonly outputs: readonly [{ + readonly internalType: "uint8"; + readonly name: ""; + readonly type: "uint8"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "to"; + readonly type: "address"; + }, { + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }]; + readonly name: "transfer"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "spender"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }]; + readonly name: "Approval"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "from"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "to"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }]; + readonly name: "Transfer"; + readonly type: "event"; + }, { + readonly constant: true; + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "spender"; + readonly type: "address"; + }]; + readonly name: "allowance"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly payable: false; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "from"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "to"; + readonly type: "address"; + }, { + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }]; + readonly name: "transferFrom"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly constant: false; + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "spender"; + readonly type: "address"; + }, { + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }]; + readonly name: "approve"; + readonly outputs: readonly []; + readonly payable: false; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly name: "nonces"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "spender"; + readonly type: "address"; + }, { + readonly internalType: "uint256"; + readonly name: "amount"; + readonly type: "uint256"; + }, { + readonly internalType: "uint256"; + readonly name: "deadline"; + readonly type: "uint256"; + }, { + readonly internalType: "uint8"; + readonly name: "v"; + readonly type: "uint8"; + }, { + readonly internalType: "bytes32"; + readonly name: "r"; + readonly type: "bytes32"; + }, { + readonly internalType: "bytes32"; + readonly name: "s"; + readonly type: "bytes32"; + }]; + readonly name: "permit"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }]; + static createInterface(): ERC20Interface; + static connect(address: string, runner?: ContractRunner | null): ERC20; +} diff --git a/dist/typechain/factories/GasPriceOracle__factory.d.ts b/dist/typechain/factories/GasPriceOracle__factory.d.ts new file mode 100644 index 0000000..8d623de --- /dev/null +++ b/dist/typechain/factories/GasPriceOracle__factory.d.ts @@ -0,0 +1,151 @@ +import { type ContractRunner } from "ethers"; +import type { GasPriceOracle, GasPriceOracleInterface } from "../GasPriceOracle"; +export declare class GasPriceOracle__factory { + static readonly abi: readonly [{ + readonly inputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "constructor"; + }, { + readonly inputs: readonly []; + readonly name: "GAS_UNIT"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint32"; + readonly name: "_derivationThresold"; + readonly type: "uint32"; + }]; + readonly name: "changeDerivationThresold"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint32"; + readonly name: "_gasUnit"; + readonly type: "uint32"; + }]; + readonly name: "changeGasUnit"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint32"; + readonly name: "_heartbeat"; + readonly type: "uint32"; + }]; + readonly name: "changeHeartbeat"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "_owner"; + readonly type: "address"; + }]; + readonly name: "changeOwnership"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "derivationThresold"; + readonly outputs: readonly [{ + readonly internalType: "uint32"; + readonly name: ""; + readonly type: "uint32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "gasPrice"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "heartbeat"; + readonly outputs: readonly [{ + readonly internalType: "uint32"; + readonly name: ""; + readonly type: "uint32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "maxFeePerGas"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "maxPriorityFeePerGas"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "pastGasPrice"; + readonly outputs: readonly [{ + readonly internalType: "uint32"; + readonly name: ""; + readonly type: "uint32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint32"; + readonly name: "_gasPrice"; + readonly type: "uint32"; + }]; + readonly name: "setGasPrice"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "timestamp"; + readonly outputs: readonly [{ + readonly internalType: "uint32"; + readonly name: ""; + readonly type: "uint32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }]; + static createInterface(): GasPriceOracleInterface; + static connect(address: string, runner?: ContractRunner | null): GasPriceOracle; +} diff --git a/dist/typechain/factories/Multicall__factory.d.ts b/dist/typechain/factories/Multicall__factory.d.ts new file mode 100644 index 0000000..2a1d4a1 --- /dev/null +++ b/dist/typechain/factories/Multicall__factory.d.ts @@ -0,0 +1,338 @@ +import { type ContractRunner } from "ethers"; +import type { Multicall, MulticallInterface } from "../Multicall"; +export declare class Multicall__factory { + static readonly abi: readonly [{ + readonly inputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "aggregate"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "blockNumber"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes[]"; + readonly name: "returnData"; + readonly type: "bytes[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "allowFailure"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call3[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "aggregate3"; + readonly outputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "bool"; + readonly name: "success"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "returnData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Result[]"; + readonly name: "returnData"; + readonly type: "tuple[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "allowFailure"; + readonly type: "bool"; + }, { + readonly internalType: "uint256"; + readonly name: "value"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call3Value[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "aggregate3Value"; + readonly outputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "bool"; + readonly name: "success"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "returnData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Result[]"; + readonly name: "returnData"; + readonly type: "tuple[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "blockAndAggregate"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "blockNumber"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes32"; + readonly name: "blockHash"; + readonly type: "bytes32"; + }, { + readonly components: readonly [{ + readonly internalType: "bool"; + readonly name: "success"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "returnData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Result[]"; + readonly name: "returnData"; + readonly type: "tuple[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getBasefee"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "basefee"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "blockNumber"; + readonly type: "uint256"; + }]; + readonly name: "getBlockHash"; + readonly outputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "blockHash"; + readonly type: "bytes32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getBlockNumber"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "blockNumber"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getChainId"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "chainid"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getCurrentBlockCoinbase"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: "coinbase"; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getCurrentBlockDifficulty"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "difficulty"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getCurrentBlockGasLimit"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "gaslimit"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getCurrentBlockTimestamp"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "timestamp"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "addr"; + readonly type: "address"; + }]; + readonly name: "getEthBalance"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "balance"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "getLastBlockHash"; + readonly outputs: readonly [{ + readonly internalType: "bytes32"; + readonly name: "blockHash"; + readonly type: "bytes32"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bool"; + readonly name: "requireSuccess"; + readonly type: "bool"; + }, { + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "tryAggregate"; + readonly outputs: readonly [{ + readonly components: readonly [{ + readonly internalType: "bool"; + readonly name: "success"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "returnData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Result[]"; + readonly name: "returnData"; + readonly type: "tuple[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bool"; + readonly name: "requireSuccess"; + readonly type: "bool"; + }, { + readonly components: readonly [{ + readonly internalType: "address"; + readonly name: "target"; + readonly type: "address"; + }, { + readonly internalType: "bytes"; + readonly name: "callData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Call[]"; + readonly name: "calls"; + readonly type: "tuple[]"; + }]; + readonly name: "tryBlockAndAggregate"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "blockNumber"; + readonly type: "uint256"; + }, { + readonly internalType: "bytes32"; + readonly name: "blockHash"; + readonly type: "bytes32"; + }, { + readonly components: readonly [{ + readonly internalType: "bool"; + readonly name: "success"; + readonly type: "bool"; + }, { + readonly internalType: "bytes"; + readonly name: "returnData"; + readonly type: "bytes"; + }]; + readonly internalType: "struct Multicall3.Result[]"; + readonly name: "returnData"; + readonly type: "tuple[]"; + }]; + readonly stateMutability: "payable"; + readonly type: "function"; + }]; + static createInterface(): MulticallInterface; + static connect(address: string, runner?: ContractRunner | null): Multicall; +} diff --git a/dist/typechain/factories/OffchainOracle__factory.d.ts b/dist/typechain/factories/OffchainOracle__factory.d.ts new file mode 100644 index 0000000..0ffeac3 --- /dev/null +++ b/dist/typechain/factories/OffchainOracle__factory.d.ts @@ -0,0 +1,404 @@ +import { type ContractRunner } from "ethers"; +import type { OffchainOracle, OffchainOracleInterface } from "../OffchainOracle"; +export declare class OffchainOracle__factory { + static readonly abi: readonly [{ + readonly inputs: readonly [{ + readonly internalType: "contract MultiWrapper"; + readonly name: "_multiWrapper"; + readonly type: "address"; + }, { + readonly internalType: "contract IOracle[]"; + readonly name: "existingOracles"; + readonly type: "address[]"; + }, { + readonly internalType: "enum OffchainOracle.OracleType[]"; + readonly name: "oracleTypes"; + readonly type: "uint8[]"; + }, { + readonly internalType: "contract IERC20[]"; + readonly name: "existingConnectors"; + readonly type: "address[]"; + }, { + readonly internalType: "contract IERC20"; + readonly name: "wBase"; + readonly type: "address"; + }, { + readonly internalType: "address"; + readonly name: "owner"; + readonly type: "address"; + }]; + readonly stateMutability: "nonpayable"; + readonly type: "constructor"; + }, { + readonly inputs: readonly []; + readonly name: "ArraysLengthMismatch"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "ConnectorAlreadyAdded"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "InvalidOracleTokenKind"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "OracleAlreadyAdded"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "SameTokens"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "TooBigThreshold"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "UnknownConnector"; + readonly type: "error"; + }, { + readonly inputs: readonly []; + readonly name: "UnknownOracle"; + readonly type: "error"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "contract IERC20"; + readonly name: "connector"; + readonly type: "address"; + }]; + readonly name: "ConnectorAdded"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "contract IERC20"; + readonly name: "connector"; + readonly type: "address"; + }]; + readonly name: "ConnectorRemoved"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "contract MultiWrapper"; + readonly name: "multiWrapper"; + readonly type: "address"; + }]; + readonly name: "MultiWrapperUpdated"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "contract IOracle"; + readonly name: "oracle"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "enum OffchainOracle.OracleType"; + readonly name: "oracleType"; + readonly type: "uint8"; + }]; + readonly name: "OracleAdded"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "contract IOracle"; + readonly name: "oracle"; + readonly type: "address"; + }, { + readonly indexed: false; + readonly internalType: "enum OffchainOracle.OracleType"; + readonly name: "oracleType"; + readonly type: "uint8"; + }]; + readonly name: "OracleRemoved"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "previousOwner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "newOwner"; + readonly type: "address"; + }]; + readonly name: "OwnershipTransferred"; + readonly type: "event"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "connector"; + readonly type: "address"; + }]; + readonly name: "addConnector"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IOracle"; + readonly name: "oracle"; + readonly type: "address"; + }, { + readonly internalType: "enum OffchainOracle.OracleType"; + readonly name: "oracleKind"; + readonly type: "uint8"; + }]; + readonly name: "addOracle"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "connectors"; + readonly outputs: readonly [{ + readonly internalType: "contract IERC20[]"; + readonly name: "allConnectors"; + readonly type: "address[]"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "contract IERC20"; + readonly name: "dstToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useWrappers"; + readonly type: "bool"; + }]; + readonly name: "getRate"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useSrcWrappers"; + readonly type: "bool"; + }]; + readonly name: "getRateToEth"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useSrcWrappers"; + readonly type: "bool"; + }, { + readonly internalType: "contract IERC20[]"; + readonly name: "customConnectors"; + readonly type: "address[]"; + }, { + readonly internalType: "uint256"; + readonly name: "thresholdFilter"; + readonly type: "uint256"; + }]; + readonly name: "getRateToEthWithCustomConnectors"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useSrcWrappers"; + readonly type: "bool"; + }, { + readonly internalType: "uint256"; + readonly name: "thresholdFilter"; + readonly type: "uint256"; + }]; + readonly name: "getRateToEthWithThreshold"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "contract IERC20"; + readonly name: "dstToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useWrappers"; + readonly type: "bool"; + }, { + readonly internalType: "contract IERC20[]"; + readonly name: "customConnectors"; + readonly type: "address[]"; + }, { + readonly internalType: "uint256"; + readonly name: "thresholdFilter"; + readonly type: "uint256"; + }]; + readonly name: "getRateWithCustomConnectors"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "srcToken"; + readonly type: "address"; + }, { + readonly internalType: "contract IERC20"; + readonly name: "dstToken"; + readonly type: "address"; + }, { + readonly internalType: "bool"; + readonly name: "useWrappers"; + readonly type: "bool"; + }, { + readonly internalType: "uint256"; + readonly name: "thresholdFilter"; + readonly type: "uint256"; + }]; + readonly name: "getRateWithThreshold"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "weightedRate"; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "multiWrapper"; + readonly outputs: readonly [{ + readonly internalType: "contract MultiWrapper"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "oracles"; + readonly outputs: readonly [{ + readonly internalType: "contract IOracle[]"; + readonly name: "allOracles"; + readonly type: "address[]"; + }, { + readonly internalType: "enum OffchainOracle.OracleType[]"; + readonly name: "oracleTypes"; + readonly type: "uint8[]"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IERC20"; + readonly name: "connector"; + readonly type: "address"; + }]; + readonly name: "removeConnector"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract IOracle"; + readonly name: "oracle"; + readonly type: "address"; + }, { + readonly internalType: "enum OffchainOracle.OracleType"; + readonly name: "oracleKind"; + readonly type: "uint8"; + }]; + readonly name: "removeOracle"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "renounceOwnership"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "contract MultiWrapper"; + readonly name: "_multiWrapper"; + readonly type: "address"; + }]; + readonly name: "setMultiWrapper"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "newOwner"; + readonly type: "address"; + }]; + readonly name: "transferOwnership"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }]; + static createInterface(): OffchainOracleInterface; + static connect(address: string, runner?: ContractRunner | null): OffchainOracle; +} diff --git a/dist/typechain/factories/OvmGasPriceOracle__factory.d.ts b/dist/typechain/factories/OvmGasPriceOracle__factory.d.ts new file mode 100644 index 0000000..73cc6a7 --- /dev/null +++ b/dist/typechain/factories/OvmGasPriceOracle__factory.d.ts @@ -0,0 +1,234 @@ +import { type ContractRunner } from "ethers"; +import type { OvmGasPriceOracle, OvmGasPriceOracleInterface } from "../OvmGasPriceOracle"; +export declare class OvmGasPriceOracle__factory { + static readonly abi: readonly [{ + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "_owner"; + readonly type: "address"; + }]; + readonly stateMutability: "nonpayable"; + readonly type: "constructor"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly name: "DecimalsUpdated"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly name: "GasPriceUpdated"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly name: "L1BaseFeeUpdated"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly name: "OverheadUpdated"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: true; + readonly internalType: "address"; + readonly name: "previousOwner"; + readonly type: "address"; + }, { + readonly indexed: true; + readonly internalType: "address"; + readonly name: "newOwner"; + readonly type: "address"; + }]; + readonly name: "OwnershipTransferred"; + readonly type: "event"; + }, { + readonly anonymous: false; + readonly inputs: readonly [{ + readonly indexed: false; + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly name: "ScalarUpdated"; + readonly type: "event"; + }, { + readonly inputs: readonly []; + readonly name: "decimals"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "gasPrice"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes"; + readonly name: "_data"; + readonly type: "bytes"; + }]; + readonly name: "getL1Fee"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "bytes"; + readonly name: "_data"; + readonly type: "bytes"; + }]; + readonly name: "getL1GasUsed"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "l1BaseFee"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "overhead"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "owner"; + readonly outputs: readonly [{ + readonly internalType: "address"; + readonly name: ""; + readonly type: "address"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "renounceOwnership"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly []; + readonly name: "scalar"; + readonly outputs: readonly [{ + readonly internalType: "uint256"; + readonly name: ""; + readonly type: "uint256"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "_decimals"; + readonly type: "uint256"; + }]; + readonly name: "setDecimals"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "_gasPrice"; + readonly type: "uint256"; + }]; + readonly name: "setGasPrice"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "_baseFee"; + readonly type: "uint256"; + }]; + readonly name: "setL1BaseFee"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "_overhead"; + readonly type: "uint256"; + }]; + readonly name: "setOverhead"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "uint256"; + readonly name: "_scalar"; + readonly type: "uint256"; + }]; + readonly name: "setScalar"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address"; + readonly name: "newOwner"; + readonly type: "address"; + }]; + readonly name: "transferOwnership"; + readonly outputs: readonly []; + readonly stateMutability: "nonpayable"; + readonly type: "function"; + }]; + static createInterface(): OvmGasPriceOracleInterface; + static connect(address: string, runner?: ContractRunner | null): OvmGasPriceOracle; +} diff --git a/dist/typechain/factories/ReverseRecords__factory.d.ts b/dist/typechain/factories/ReverseRecords__factory.d.ts new file mode 100644 index 0000000..bed38f0 --- /dev/null +++ b/dist/typechain/factories/ReverseRecords__factory.d.ts @@ -0,0 +1,29 @@ +import { type ContractRunner } from "ethers"; +import type { ReverseRecords, ReverseRecordsInterface } from "../ReverseRecords"; +export declare class ReverseRecords__factory { + static readonly abi: readonly [{ + readonly inputs: readonly [{ + readonly internalType: "contract ENS"; + readonly name: "_ens"; + readonly type: "address"; + }]; + readonly stateMutability: "nonpayable"; + readonly type: "constructor"; + }, { + readonly inputs: readonly [{ + readonly internalType: "address[]"; + readonly name: "addresses"; + readonly type: "address[]"; + }]; + readonly name: "getNames"; + readonly outputs: readonly [{ + readonly internalType: "string[]"; + readonly name: "r"; + readonly type: "string[]"; + }]; + readonly stateMutability: "view"; + readonly type: "function"; + }]; + static createInterface(): ReverseRecordsInterface; + static connect(address: string, runner?: ContractRunner | null): ReverseRecords; +} diff --git a/dist/typechain/factories/index.d.ts b/dist/typechain/factories/index.d.ts new file mode 100644 index 0000000..ab90b86 --- /dev/null +++ b/dist/typechain/factories/index.d.ts @@ -0,0 +1,7 @@ +export { ENS__factory } from "./ENS__factory"; +export { ERC20__factory } from "./ERC20__factory"; +export { GasPriceOracle__factory } from "./GasPriceOracle__factory"; +export { Multicall__factory } from "./Multicall__factory"; +export { OffchainOracle__factory } from "./OffchainOracle__factory"; +export { OvmGasPriceOracle__factory } from "./OvmGasPriceOracle__factory"; +export { ReverseRecords__factory } from "./ReverseRecords__factory"; diff --git a/dist/typechain/index.d.ts b/dist/typechain/index.d.ts new file mode 100644 index 0000000..7f5f66e --- /dev/null +++ b/dist/typechain/index.d.ts @@ -0,0 +1,15 @@ +export type { ENS } from "./ENS"; +export type { ERC20 } from "./ERC20"; +export type { GasPriceOracle } from "./GasPriceOracle"; +export type { Multicall } from "./Multicall"; +export type { OffchainOracle } from "./OffchainOracle"; +export type { OvmGasPriceOracle } from "./OvmGasPriceOracle"; +export type { ReverseRecords } from "./ReverseRecords"; +export * as factories from "./factories"; +export { ENS__factory } from "./factories/ENS__factory"; +export { ERC20__factory } from "./factories/ERC20__factory"; +export { GasPriceOracle__factory } from "./factories/GasPriceOracle__factory"; +export { Multicall__factory } from "./factories/Multicall__factory"; +export { OffchainOracle__factory } from "./factories/OffchainOracle__factory"; +export { OvmGasPriceOracle__factory } from "./factories/OvmGasPriceOracle__factory"; +export { ReverseRecords__factory } from "./factories/ReverseRecords__factory"; diff --git a/dist/utils.d.ts b/dist/utils.d.ts new file mode 100644 index 0000000..8ffe743 --- /dev/null +++ b/dist/utils.d.ts @@ -0,0 +1,27 @@ +/// +/// +import { webcrypto } from 'crypto'; +import BN from 'bn.js'; +import type { BigNumberish } from 'ethers'; +type bnInput = number | string | number[] | Uint8Array | Buffer | BN; +export declare const isNode: boolean; +export declare const crypto: webcrypto.Crypto; +export declare const chunk: (arr: T[], size: number) => T[][]; +export declare function sleep(ms: number): Promise; +export declare function validateUrl(url: string, protocols?: string[]): boolean; +export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array; +export declare function bufferToBytes(b: Buffer): Uint8Array; +export declare function bytesToBase64(bytes: Uint8Array): string; +export declare function base64ToBytes(base64: string): Uint8Array; +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function hexToBytes(hexString: string): Uint8Array; +export declare function bytesToBN(bytes: Uint8Array): bigint; +export declare function bnToBytes(bigint: bigint | string): Uint8Array; +export declare function leBuff2Int(bytes: Uint8Array): BN; +export declare function leInt2Buff(bigint: bnInput | bigint): Uint8Array; +export declare function toFixedHex(numberish: BigNumberish, length?: number): string; +export declare function toFixedLength(string: string, length?: number): string; +export declare function rBigInt(nbytes?: number): bigint; +export declare function bigIntReplacer(key: any, value: any): any; +export declare function substring(str: string, length?: number): string; +export {}; diff --git a/dist/websnark.d.ts b/dist/websnark.d.ts new file mode 100644 index 0000000..461d57a --- /dev/null +++ b/dist/websnark.d.ts @@ -0,0 +1,27 @@ +import type { Element } from '@tornado/fixed-merkle-tree'; +import type { AddressLike, BytesLike, BigNumberish } from 'ethers'; +export type snarkInputs = { + root: Element; + nullifierHex: string; + recipient: AddressLike; + relayer: AddressLike; + fee: bigint; + refund: bigint; + nullifier: bigint; + secret: bigint; + pathElements: Element[]; + pathIndices: Element[]; +}; +export type snarkArgs = [ + _root: BytesLike, + _nullifierHash: BytesLike, + _recipient: AddressLike, + _relayer: AddressLike, + _fee: BigNumberish, + _refund: BigNumberish +]; +export type snarkProofs = { + proof: BytesLike; + args: snarkArgs; +}; +export declare function calculateSnarkProof(input: snarkInputs, circuit: object, provingKey: ArrayBuffer): Promise;