/// /// import { Signature } from '@railgun-community/circomlibjs'; import EventEmitter from 'events'; import { BigNumberish, ContractTransaction } from 'ethers'; import { Database } from '../database/database'; import { SpendingPublicKey, ViewingKeyPair } from '../key-derivation/wallet-node'; import { UnshieldStoredEvent } from '../models/event-types'; import { BytesData, Commitment } from '../models/formatted-types'; import { SentCommitment, TXO, TXOsReceivedPOIStatusInfo, TXOsSpentPOIStatusInfo, WalletBalanceBucket } from '../models/txo-types'; import { AddressKeys, TokenBalancesAllTxidVersions, TotalBalancesByTreeNumber, TokenBalances, TransactionHistoryEntry, TreeBalance, ViewOnlyWalletData, WalletData, WalletDetails, WalletDetailsMap } from '../models/wallet-types'; import { Chain } from '../models/engine-types'; import { PrivateInputsRailgun, PublicInputsRailgun } from '../models/prover-types'; import { UTXOMerkletree } from '../merkletree/utxo-merkletree'; import { TXIDMerkletree } from '../merkletree/txid-merkletree'; import { PreTransactionPOI, PreTransactionPOIsPerTxidLeafPerList, TXIDVersion } from '../models/poi-types'; import { Prover } from '../prover/prover'; import { ExtractedRailgunTransactionData } from '../models/transaction-types'; import { Registry } from '../utils/registry'; import { SigningAttempt, SigningEnvelope } from '../solutions/nullifiers'; declare abstract class AbstractWallet extends EventEmitter { protected readonly db: Database; private readonly tokenDataGetter; readonly id: string; readonly viewingKeyPair: ViewingKeyPair; readonly masterPublicKey: bigint; private readonly spendingPublicKey; readonly nullifyingKey: bigint; private readonly utxoMerkletrees; private readonly txidMerkletrees; readonly isRefreshingPOIs: Registry; private readonly prover; private readonly isClearingBalances; private readonly decryptBalancesKeyForChain; private creationBlockNumbers; private generatingPOIsForChain; private receiveCommitmentsCache; private sentCommitmentsCache; /** * Create Wallet controller * @param id - wallet ID * @param db - database */ constructor(id: string, db: Database, viewingKeyPair: ViewingKeyPair, spendingPublicKey: SpendingPublicKey, creationBlockNumbers: Optional, prover: Prover); /** * Loads utxo merkle tree into wallet */ loadUTXOMerkletree(txidVersion: TXIDVersion, utxoMerkletree: UTXOMerkletree): Promise; /** * Unload utxo merkle tree by chain */ unloadUTXOMerkletree(txidVersion: TXIDVersion, chain: Chain): void; /** * Loads txid merkle tree into wallet */ loadRailgunTXIDMerkletree(txidVersion: TXIDVersion, txidMerkletree: TXIDMerkletree): void; /** * Unload txid merkle tree by chain */ unloadRailgunTXIDMerkletree(txidVersion: TXIDVersion, chain: Chain): void; private getUTXOMerkletreeHistoryVersionDBPrefix; setUTXOMerkletreeHistoryVersion(chain: Chain, merkletreeHistoryVersion: number): Promise; getUTXOMerkletreeHistoryVersion(chain: Chain): Promise>; private emitPOIProofUpdateEvent; /** * Construct DB TXO path from chain * Prefix consists of ['wallet', id, chain] * May be appended with tree and position * @param chain - chain type/id * @optional tree - without this param, all trees * @optional position - without this param, all positions * @returns wallet DB prefix */ getWalletDBPrefix(chain: Chain, tree?: number, position?: number): string[]; /** * Construct DB received commitment path from chain * Prefix consists of ['wallet', id, chain] */ getWalletReceiveCommitmentDBPrefix(chain: Chain, tree: number, position: number): string[]; /** * Construct DB spent commitment path from chain * Prefix consists of ['wallet', id + "-spent", chain] * May be appended with tree and position * @param chain - chain type/id * @optional tree - without this param, all trees * @optional position - without this param, all positions * @returns wallet DB prefix */ getWalletSentCommitmentDBPrefix(chain: Chain, tree?: number, position?: number): string[]; /** * Construct DB path from chain * @returns wallet DB path */ getWalletDetailsPath(chain: Chain): string[]; /** * Return object of Viewing privateKey and pubkey * @returns {ViewingKeyPair} */ getViewingKeyPair(): ViewingKeyPair; /** * Used only to sign Broadcaster fee messages. * Verified using Broadcaster's viewingPublicKey, which is encoded in its rail address. * @param {Uint8Array} message - message to sign as Uint8Array */ signWithViewingKey(message: Uint8Array): Promise; /** * Nullifying Key (ie poseidon hash of Viewing Private Key) aka vpk derived on ed25519 curve * Used to decrypt and nullify notes * @returns {bigint} */ getNullifyingKey(): bigint; /** * Get Viewing Public Key (VK) * @returns {Uint8Array} */ get viewingPublicKey(): Uint8Array; /** * Transaction shapes this wallet's signer can actually produce. Defaults to the circuit * envelope; a hardware wallet narrows it when its device imposes tighter limits. * Consulted before UTXOs are selected, so a batch is never built that the signer will * refuse after the user has approved it. */ get signingEnvelope(): SigningEnvelope; /** * Ways this wallet is willing to sign a batch, in preference order. The batch tries each * in turn and keeps the first whose envelope can satisfy the request, so a later entry is * a fallback, not an alternative the caller picks. * * A software wallet has exactly one: blind signing over the full circuit envelope. Only a * hardware wallet that can clear-sign offers more than one. */ get signingAttempts(): readonly SigningAttempt[]; /** * Return masterPublicKey and viewingPublicKey used to encode RAILGUN addresses * @returns {AddressKeys} */ get addressKeys(): AddressKeys; /** * Encode address from (MPK, VK) + chain * @returns {string} bech32 encoded RAILGUN address */ getAddress(chain?: Chain): string; getWalletDetailsMap(chain: Chain): Promise; /** * Get encrypted wallet details for this wallet * @param chain - chain type/id * @returns walletDetails - including treeScannedHeight */ getWalletDetails(txidVersion: TXIDVersion, chain: Chain): Promise; private decryptLeaf; private static getCommitmentType; private createScannedDBCommitments; /** * Scans wallet at index for new balances * Commitment index in array should be same as commitment index in tree * @param {Commitment[]} leaves - commitments from events to attempt parsing * @param {number} tree - tree number we're scanning * @param {number} chain - chain type/id we're scanning * @param {number} startScanHeight - starting position */ scanLeaves(txidVersion: TXIDVersion, leaves: Optional[], tree: number, chain: Chain, startScanHeight: number, scanTicker: Optional<() => void>): Promise; private keySplits; private queryAllStoredReceiveCommitments; private queryAllStoredSendCommitments; /** * Clears commitments cache */ invalidateCommitmentsCache(chain: Chain): void; /** * Get TXOs list of a chain * @param chain - chain type/id to get UTXOs for * @returns UTXOs list */ TXOs(txidVersion: TXIDVersion, chain: Chain): Promise; /** * Get spent commitments of a chain * @param chain - chain type/id to get spent commitments for * @returns SentCommitment list */ private getSentCommitments; private updateReceiveCommitmentInDB; private updateSentCommitmentInDB; getTXOsReceivedPOIStatusInfo(txidVersion: TXIDVersion, chain: Chain): Promise; getTXOsSpentPOIStatusInfo(txidVersion: TXIDVersion, chain: Chain): Promise; getNumSpendPOIProofsPossible(txidVersion: TXIDVersion, chain: Chain): Promise; submitLegacyTransactPOIEventsReceiveCommitments(txidVersion: TXIDVersion, chain: Chain): Promise; receiveCommitmentHasValidPOI(txidVersion: TXIDVersion, chain: Chain, commitment: string): Promise; getChainTxidsStillPendingSpentPOIs(txidVersion: TXIDVersion, chain: Chain): Promise; getSpendableReceivedChainTxids(txidVersion: TXIDVersion, chain: Chain): Promise; refreshReceivePOIsAllTXOs(txidVersion: TXIDVersion, chain: Chain): Promise; private static sortPOIsPerListUndefinedFirst; private static filterByRailgunTxid; getSentCommitmentsAndUnshieldEventsNeedPOIRefresh(txidVersion: TXIDVersion, chain: Chain, filterRailgunTxid?: string): Promise<{ sentCommitmentsNeedPOIRefresh: SentCommitment[]; unshieldEventsNeedPOIRefresh: UnshieldStoredEvent[]; TXOs: TXO[]; }>; getSentCommitmentsAndUnshieldEventsNeedPOIs(txidVersion: TXIDVersion, chain: Chain, filterRailgunTxid?: string): Promise<{ sentCommitments: SentCommitment[]; sentCommitmentsNeedPOIs: SentCommitment[]; unshieldEvents: UnshieldStoredEvent[]; unshieldEventsNeedPOIs: UnshieldStoredEvent[]; TXOs: TXO[]; }>; refreshSpentPOIsAllSentCommitmentsAndUnshieldEvents(txidVersion: TXIDVersion, chain: Chain, filterRailgunTxid?: string): Promise; generatePOIsAllSentCommitmentsAndUnshieldEvents(chain: Chain, txidVersion: TXIDVersion, railgunTxidFilter?: string): Promise; generatePreTransactionPOI(txidVersion: TXIDVersion, chain: Chain, listKey: string, utxos: TXO[], publicInputs: PublicInputsRailgun, privateInputs: PrivateInputsRailgun, treeNumber: BigNumberish, hasUnshield: boolean, progressCallback: (progress: number) => void): Promise<{ txidLeafHash: string; preTransactionPOI: PreTransactionPOI; }>; private generatePOIsForRailgunTxidAndListKey; isValidSpendableTransaction(txidVersion: TXIDVersion, chain: Chain, contractAddress: string, transactionRequest: ContractTransaction, useRelayAdapt: boolean, pois: PreTransactionPOIsPerTxidLeafPerList, useRelayAdapt7702?: boolean): Promise<{ isValid: boolean; error?: string; extractedRailgunTransactionData?: ExtractedRailgunTransactionData; }>; private static getListPOIMerkleProofs; private updateReceiveCommitmentCreatedPOIs; private updateSentCommitmentSpentPOIs; private static getPossibleChangeTokenAmounts; /** * Gets transactions history * @param chain - chain type/id to get transaction history for * @returns history */ getTransactionHistory(chain: Chain, startingBlock: Optional): Promise; private getTransactionHistoryByTXIDVersion; private static filterTXOsByBlockNumber; extractFirstNoteERC20AmountMap(txidVersion: TXIDVersion, chain: Chain, transactionRequest: ContractTransaction, useRelayAdapt: boolean, contractAddress: string, useRelayAdapt7702?: boolean): Promise>; /** * Gets transactions history for "received" transactions * @param chain - chain type/id to get balances for * @returns history */ private static getTransactionReceiveHistory; private static getTransactionHistoryItemVersion; /** * NOTE: There are no Unshield events pre-V2. */ getUnshieldEventsFromSpentNullifiers(txidVersion: TXIDVersion, chain: Chain, filteredTXOs: TXO[]): Promise; private static compareUnshieldEvents; private getTransactionSpendHistory; getUTXOMerkletree(txidVersion: TXIDVersion, chain: Chain): UTXOMerkletree; private hasUTXOMerkletree; getRailgunTXIDMerkletreeForChain(txidVersion: TXIDVersion, chain: Chain): TXIDMerkletree; getTokenBalancesAllTxidVersions(chain: Chain, balanceBucketFilter: WalletBalanceBucket[]): Promise; getTokenBalances(txidVersion: TXIDVersion, chain: Chain, onlySpendable: boolean): Promise; /** * Gets the balances an unshield-to-origin may spend: the unspent shield notes of the given * shield txid whose Private POI is still pending (ShieldPending) or blocked (ShieldBlocked). * Notes of that shield with a valid Private POI are spendable as usual and are not included. * @param originShieldTxidForSpendabilityOverride - txid of the shield to reverse * @returns balances */ getTokenBalancesForUnshieldToOrigin(txidVersion: TXIDVersion, chain: Chain, originShieldTxidForSpendabilityOverride?: string): Promise; getTokenBalancesByBucket(txidVersion: TXIDVersion, chain: Chain): Promise>; /** * Gets wallet balances * @param chain - chain type/id to get balances for * @returns balances */ static getTokenBalancesByTxidVersion(TXOs: TXO[], balanceBucketFilter: WalletBalanceBucket[], originShieldTxidForSpendabilityOverride?: string): Promise; getBalanceERC20(txidVersion: TXIDVersion, chain: Chain, tokenAddress: string, balanceBucketFilter: WalletBalanceBucket[]): Promise>; /** * Sort token balances by tree * @param chain - chain type/id of token * @returns balances by tree */ getTotalBalancesByTreeNumber(txidVersion: TXIDVersion, chain: Chain, balanceBucketFilter: WalletBalanceBucket[], originShieldTxidForSpendabilityOverride?: string): Promise; balancesByTreeForToken(txidVersion: TXIDVersion, chain: Chain, tokenHash: string, balanceBucketFilter: WalletBalanceBucket[], originShieldTxidForSpendabilityOverride?: string): Promise; static tokenBalanceAcrossAllTrees(treeSortedBalances: TreeBalance[]): bigint; decryptBalances(txidVersion: TXIDVersion, chain: Chain, progressCallback: Optional<(progress: number) => void>, deferCompletionEvent: boolean): Promise; refreshPOIsForAllTXIDVersions(chain: Chain, forceRefresh?: boolean): Promise; /** * Occurs after balances are scanned. */ refreshPOIsForTXIDVersion(chain: Chain, txidVersion: TXIDVersion, forceRefresh?: boolean): Promise; generatePOIsForRailgunTxid(chain: Chain, txidVersion: TXIDVersion, railgunTxid: string): Promise; /** * Searches for creation tree height for given merkletree based on creationBlockNumber. * Will return the latest position that is <= creationBlockNumber. May return an index that has blockNumber < creationBlockNumber, * but that is okay for purposes of creationTreeHeight. We just need to guarantee we don't return a position that misses some commitments in the creation block. * @param merkletree - Merkletree * @param latestTree - number */ static getCreationTreeAndPosition(utxoMerkletree: UTXOMerkletree, latestTree: number, creationBlockNumber: number): Promise>; /** * @warning This method is ONLY intended for testing purposes. */ testSpecificSetCreationBlockNumbers(creationBlockNumbers: Optional): void; /** * Clears balances decrypted from merkletrees and stored to database. * @param chain - chain type/id to clear */ clearDecryptedBalancesAllTXIDVersions(chain: Chain): Promise; /** * Clears stored balances and re-decrypts fully. * @param chain - chain type/id to rescan */ fullRedecryptBalancesAllTXIDVersions(chain: Chain, progressCallback: Optional<(progress: number) => void>): Promise; abstract sign(publicInputs: PublicInputsRailgun, encryptionKey: string): Promise; static dbPath(id: string): BytesData[]; static read(db: Database, id: string, encryptionKey: string): Promise; static write(db: Database, id: string, encryptionKey: string, data: WalletData | ViewOnlyWalletData): Promise; static delete(db: Database, id: string): Promise; /** * Loads encrypted wallet data from database. * @param db - database * @param encryptionKey - encryption key to use with database * @param id - wallet id */ static getEncryptedData(db: Database, encryptionKey: string, id: string): Promise; static getKeysFromShareableViewingKey(shareableViewingKey: string): { viewingPrivateKey: string; spendingPublicKey: SpendingPublicKey; }; generateShareableViewingKey(): string; } export { AbstractWallet };