import { PendingUMPUpdate, SignedUMPActionReceipt, WalletStatePersistence, WalletStateTransitionError, WalletProfileUnavailableError, UMPActionCheckpoint, validatePendingUMPUpdate } from './WalletStatePersistence' import { readUMPActionReceipt, umpUpdateActionLabel } from './utility/umpActionReceipt' export * from './WalletStatePersistence' import { awaitFromSync, promiseFromSync, mapAwaitFromSync } from './utility/promiseFromSync' import { Random, SymmetricKey, AbortActionArgs, AbortActionResult, AcquireCertificateArgs, AcquireCertificateResult, AuthenticatedResult, CreateActionArgs, CreateActionResult, CreateHmacArgs, CreateHmacResult, CreateSignatureArgs, CreateSignatureResult, DiscoverByAttributesArgs, DiscoverByIdentityKeyArgs, DiscoverCertificatesResult, GetHeaderArgs, GetHeaderResult, GetHeightResult, GetNetworkResult, GetPublicKeyArgs, GetPublicKeyResult, GetVersionResult, InternalizeActionArgs, InternalizeActionResult, ListActionsArgs, ListActionsResult, ListCertificatesArgs, ListCertificatesResult, ListOutputsArgs, ListOutputsResult, OriginatorDomainNameStringUnder250Bytes, ProveCertificateArgs, ProveCertificateResult, RelinquishCertificateArgs, RelinquishCertificateResult, RelinquishOutputArgs, RelinquishOutputResult, RevealCounterpartyKeyLinkageArgs, RevealCounterpartyKeyLinkageResult, RevealSpecificKeyLinkageArgs, RevealSpecificKeyLinkageResult, SignActionArgs, SignActionResult, VerifyHmacArgs, VerifyHmacResult, VerifySignatureArgs, VerifySignatureResult, WalletDecryptArgs, WalletDecryptResult, WalletEncryptArgs, WalletEncryptResult, WalletInterface, OutpointString, PrivateKey, ProtoWallet, Signature, LookupResolver, LookupAnswer, LookupResolution, Beef, Spend, Transaction, PushDrop, LockingScript, CreateActionInput, SHIPBroadcaster, Telemetry, TelemetryConfig, completeBoundAction, decodeCanonicalPushDrop } from '@bsv/sdk' import { sha256 } from '@bsv/sdk/primitives/Hash' import { Reader, Writer, toArray, toHex, toUTF8 } from '@bsv/sdk/primitives/utils' import { PrivilegedKeyManager } from './sdk/PrivilegedKeyManager' import { argon2id, createSHA256, createSHA512, pbkdf2 } from './utility/hashWasm' const CWI_COMPONENT = 'wallet-toolbox.cwi-manager' /** * Number of rounds used in PBKDF2 for deriving password keys. */ export const PBKDF2_NUM_ROUNDS = 7777 /** * Default Argon2id parameters for password-key derivation (UMP v3). */ export const ARGON2ID_DEFAULT_ITERATIONS = 7 export const ARGON2ID_DEFAULT_MEMORY_KIB = 131072 export const ARGON2ID_DEFAULT_PARALLELISM = 1 export const ARGON2ID_DEFAULT_HASH_LENGTH = 32 export const ARGON2ID_MAX_ITERATIONS = 20 export const ARGON2ID_MAX_MEMORY_KIB = 262144 export const ARGON2ID_MAX_PARALLELISM = 16 export const KDF_MAX_HASH_LENGTH = 64 export const PBKDF2_MAX_ITERATIONS = 10_000_000 export const MAX_STATE_SNAPSHOT_BYTES = 16 * 1024 * 1024 const MAX_PENDING_REGISTRATION_TOKEN_BYTES = 64 * 1024 function readSerializedOutpoint(reader: Reader, allowUnpublished: boolean): string { const outpointLen = reader.readVarIntNumStrict(false) const currentOutpoint = toUTF8(reader.read(outpointLen)) if ( (currentOutpoint.length === 0 && !allowUnpublished) || currentOutpoint.length > 128 || (currentOutpoint.length > 0 && !/^[^\s.:]+[.:]\d+$/.test(currentOutpoint)) || (allowUnpublished && !reader.eof()) ) { throw new Error('Serialized UMP token contains an invalid outpoint.') } return currentOutpoint } function isPositiveIntegerInRange(value: unknown, maximum: number): value is number { return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= maximum } function isValidKdfConfig(kdf: UMPToken['passwordKdf']): boolean { if (kdf == null) return false if ( !isPositiveIntegerInRange( kdf.iterations, kdf.algorithm === 'argon2id' ? ARGON2ID_MAX_ITERATIONS : PBKDF2_MAX_ITERATIONS ) ) { return false } if (kdf.algorithm === 'pbkdf2-sha512') { return kdf.hashLength === undefined || isPositiveIntegerInRange(kdf.hashLength, KDF_MAX_HASH_LENGTH) } if (kdf.algorithm !== 'argon2id') return false return ( isPositiveIntegerInRange(kdf.memoryKiB, ARGON2ID_MAX_MEMORY_KIB) && isPositiveIntegerInRange(kdf.parallelism, ARGON2ID_MAX_PARALLELISM) && isPositiveIntegerInRange(kdf.hashLength, KDF_MAX_HASH_LENGTH) ) } function findKdfVersionFieldIndex(protocolFields: number[][]): number { const hasMetadataWithProfiles = protocolFields.length >= 15 && protocolFields[12]?.length === 1 && protocolFields[12][0] === 3 if (hasMetadataWithProfiles) return 12 const hasMetadataWithoutProfiles = protocolFields.length >= 14 && protocolFields[11]?.length === 1 && protocolFields[11][0] === 3 return hasMetadataWithoutProfiles ? 11 : -1 } function addProfilesField(token: UMPToken, protocolFields: number[][], kdfVersionFieldIndex: number): boolean { const hasProfilesField = kdfVersionFieldIndex === 12 || (kdfVersionFieldIndex !== 11 && protocolFields[11] != null) if (!hasProfilesField || protocolFields[11].length === 0) return true if (protocolFields[11].length > MAX_STATE_SNAPSHOT_BYTES) return false token.profilesEncrypted = protocolFields[11] return true } function addPasswordKdf(token: UMPToken, protocolFields: number[][], kdfVersionFieldIndex: number): boolean { if (kdfVersionFieldIndex === -1) return true const kdfAlgorithmField = protocolFields[kdfVersionFieldIndex + 1] const kdfParamsField = protocolFields[kdfVersionFieldIndex + 2] if (kdfAlgorithmField == null || kdfParamsField == null || kdfParamsField.length > 1024) { return false } const kdfParams = JSON.parse(toUTF8(kdfParamsField)) as Record const passwordKdf: UMPToken['passwordKdf'] = { algorithm: toUTF8(kdfAlgorithmField) as 'pbkdf2-sha512' | 'argon2id', iterations: kdfParams.iterations as number, memoryKiB: kdfParams.memoryKiB as number | undefined, parallelism: kdfParams.parallelism as number | undefined, hashLength: kdfParams.hashLength as number | undefined } if (!isValidKdfConfig(passwordKdf)) return false token.umpVersion = 3 token.passwordKdf = passwordKdf return true } function isLikelyDerSignatureField(field: number[]): boolean { if (!field || field.length < 8 || field.length > 80) { return false } if (field[0] !== 0x30) { return false } const declaredLen = field[1] return declaredLen === field.length - 2 } function stripVerifiedPushDropSignature(fields: number[][], lockingPublicKey: any): number[][] { if (fields.length <= 11) { return fields } const protocolFieldCount = fields.length - 1 const trailingField = fields[protocolFieldCount] if (!trailingField || !isLikelyDerSignatureField(trailingField)) { return fields } try { let dataLength = 0 for (let i = 0; i < protocolFieldCount; i++) { dataLength += fields[i].length } const dataToVerify = Array.from({ length: dataLength }, () => 0) let writeOffset = 0 for (let i = 0; i < protocolFieldCount; i++) { const field = fields[i] for (const byte of field) { dataToVerify[writeOffset++] = byte } } const signature = Signature.fromDER(trailingField) if (signature.verify(dataToVerify, lockingPublicKey)) { return fields.slice(0, protocolFieldCount) } } catch { return fields } return fields } function decodeAuthenticatedUMPFields(lockingScript: LockingScript): ReturnType { const decoded = decodeCanonicalPushDrop(lockingScript, { fieldCount: [12, 13, 15, 16], maximumFieldBytes: MAX_STATE_SNAPSHOT_BYTES, maximumPayloadBytes: MAX_STATE_SNAPSHOT_BYTES }) const fields = stripVerifiedPushDropSignature(decoded.fields, decoded.lockingPublicKey) if (fields.length !== decoded.fields.length - 1) { throw new Error('UMP token field signature is missing or invalid') } const kdfVersionFieldIndex = findKdfVersionFieldIndex(fields) if ( (kdfVersionFieldIndex === -1 && fields.length > 12) || (kdfVersionFieldIndex === 11 && fields.length !== 14) || (kdfVersionFieldIndex === 12 && fields.length !== 15) ) { throw new Error('UMP token field layout is invalid') } return { ...decoded, fields } } /** * PBKDF-2 that prefers WebCrypto and falls back to hash-wasm. * * @param passwordBytes Raw password bytes. * @param salt Salt bytes. * @param iterations Number of rounds. * @param keyLen Desired key length in bytes. * @param hash Digest algorithm (default "sha512"). * @returns Derived key bytes. */ async function pbkdf2NativeOrWasm( passwordBytes: number[], salt: number[], iterations: number, keyLen: number, hash: 'sha256' | 'sha512' = 'sha512' ): Promise { // ----- fast-path: WebCrypto (both browser & recent Node expose globalThis.crypto.subtle) const subtle = (globalThis as any)?.crypto?.subtle as SubtleCrypto | undefined if (subtle != null) { try { const baseKey = await subtle.importKey( 'raw', new Uint8Array(passwordBytes), { name: 'PBKDF2' }, /* extractable */ false, ['deriveBits'] ) const bits = await subtle.deriveBits( { name: 'PBKDF2', salt: new Uint8Array(salt), iterations, hash: hash.toUpperCase() as AlgorithmIdentifier }, baseKey, keyLen * 8 ) return Array.from(new Uint8Array(bits)) } catch { // WebCrypto is unavailable or refused the algorithm (e.g. non-secure context, old // Safari). Fall through to the pure-JS hash-wasm implementation below. } } const hashFunction = hash === 'sha256' ? createSHA256() : createSHA512() const derived = await pbkdf2({ password: new Uint8Array(passwordBytes), salt: new Uint8Array(salt), iterations, hashLength: keyLen, hashFunction, outputType: 'binary' }) return Array.from(derived) } /** * Derives the password key from a password using the KDF specified in the UMP token. * For legacy tokens (no KDF metadata), uses PBKDF2 with fixed rounds (7777). * For v3 tokens, uses the algorithm specified in passwordKdf metadata. * * @param token The UMP token containing KDF metadata and salt. * @param passwordBytes Raw password bytes. * @param overrideKdf Optional KDF config to override token/default settings. * @returns Derived password key bytes. */ async function derivePasswordKey( token: Pick, passwordBytes: number[], overrideKdf?: { algorithm?: 'pbkdf2-sha512' | 'argon2id' iterations?: number memoryKiB?: number parallelism?: number hashLength?: number } ): Promise { const kdf = overrideKdf || token.passwordKdf if (kdf != null && !isValidKdfConfig(kdf as UMPToken['passwordKdf'])) { throw new Error('UMP token contains unsupported or unsafe KDF parameters.') } // Legacy token or explicit PBKDF2 request if (kdf == null || kdf.algorithm === 'pbkdf2-sha512') { return await pbkdf2NativeOrWasm( passwordBytes, token.passwordSalt, kdf?.iterations ?? PBKDF2_NUM_ROUNDS, 32, 'sha512' ) } // Argon2id path (UMP v3) if (kdf.algorithm === 'argon2id') { const iterations = kdf.iterations ?? ARGON2ID_DEFAULT_ITERATIONS const memorySize = kdf.memoryKiB ?? ARGON2ID_DEFAULT_MEMORY_KIB const parallelism = kdf.parallelism ?? ARGON2ID_DEFAULT_PARALLELISM const hashLength = kdf.hashLength ?? ARGON2ID_DEFAULT_HASH_LENGTH const hash = await argon2id({ password: new Uint8Array(passwordBytes), salt: new Uint8Array(token.passwordSalt), iterations, memorySize, parallelism, hashLength, outputType: 'binary' }) return Array.from(hash) } throw new Error(`Unsupported KDF algorithm: ${(kdf as any).algorithm}`) } /** * Unique Identifier for the default profile (16 zero bytes). */ export const DEFAULT_PROFILE_ID = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] /** * Describes the structure of a user profile within the wallet. */ export interface Profile { /** * User-defined name for the profile. */ name: string /** * Unique 16-byte identifier for the profile. */ id: number[] /** * 32-byte random pad XOR'd with the root primary key to derive the profile's primary key. */ primaryPad: number[] /** * 32-byte random pad XOR'd with the root privileged key to derive the profile's privileged key. */ privilegedPad: number[] /** * Timestamp (seconds since epoch) when the profile was created. */ createdAt: number } function isByteArrayOfLength(value: unknown, length: number): value is number[] { return ( Array.isArray(value) && value.length === length && value.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255) ) } function isValidProfile(value: unknown): value is Profile { if (value == null || typeof value !== 'object') return false const profile = value as Partial return ( typeof profile.name === 'string' && profile.name.length > 0 && profile.name.length <= 250 && isByteArrayOfLength(profile.id, 16) && isByteArrayOfLength(profile.primaryPad, 32) && isByteArrayOfLength(profile.privilegedPad, 32) && typeof profile.createdAt === 'number' && Number.isFinite(profile.createdAt) && profile.createdAt >= 0 ) } /** * Describes the structure of a User Management Protocol (UMP) token. */ export interface UMPToken { /** * Root Primary key encrypted by the XOR of the password and presentation keys. */ passwordPresentationPrimary: number[] /** * Root Primary key encrypted by the XOR of the password and recovery keys. */ passwordRecoveryPrimary: number[] /** * Root Primary key encrypted by the XOR of the presentation and recovery keys. */ presentationRecoveryPrimary: number[] /** * Root Privileged key encrypted by the XOR of the password and primary keys. */ passwordPrimaryPrivileged: number[] /** * Root Privileged key encrypted by the XOR of the presentation and recovery keys. */ presentationRecoveryPrivileged: number[] /** * Hash of the presentation key. */ presentationHash: number[] /** * PBKDF2 salt used in conjunction with the password to derive the password key. */ passwordSalt: number[] /** * Hash of the recovery key. */ recoveryHash: number[] /** * A copy of the presentation key encrypted with the root privileged key. */ presentationKeyEncrypted: number[] /** * A copy of the recovery key encrypted with the root privileged key. */ recoveryKeyEncrypted: number[] /** * A copy of the password key encrypted with the root privileged key. */ passwordKeyEncrypted: number[] /** * Optional field containing the encrypted profile data. * JSON string -> Encrypted Bytes using root privileged key. */ profilesEncrypted?: number[] /** * On-chain UMP protocol version (3 for tokens with KDF metadata). */ umpVersion?: number /** * Password-based key derivation function metadata. * Present for UMP v3 tokens; absent for legacy tokens. */ passwordKdf?: { algorithm: 'pbkdf2-sha512' | 'argon2id' iterations: number memoryKiB?: number parallelism?: number hashLength?: number } /** * Describes the token's location on-chain, if it's already been published. */ currentOutpoint?: OutpointString } /** * Configuration options for KDF (Key Derivation Function) used in UMP tokens. */ export interface KdfConfig { /** * Algorithm to use for new UMP tokens. */ algorithm?: 'pbkdf2-sha512' | 'argon2id' /** * Number of iterations/rounds. */ iterations?: number /** * Memory size in KiB (Argon2id only). */ memoryKiB?: number /** * Degree of parallelism (Argon2id only). */ parallelism?: number /** * Hash output length in bytes. */ hashLength?: number } /** * Describes a system capable of finding and updating UMP tokens on the blockchain. */ export interface UMPTokenInteractor { /** Opt-in checkpoint/republication contract; custom interactors must explicitly implement it. */ readonly checkpointVersion?: 1 /** Verify that a discovered token is controlled by the authenticated root wallet. */ verifyToken?: ( wallet: Pick, adminOriginator: string, token: UMPToken ) => Promise /** Return the original signed action from durable wallet storage, when available. */ recoverCheckpoint?: ( wallet: WalletInterface, adminOriginator: string, token: UMPToken, previousToken: UMPToken, checkpoint: PendingUMPUpdate ) => Promise publishCheckpoint?: ( wallet: WalletInterface, adminOriginator: string, token: UMPToken, previousToken: UMPToken, checkpoint: PendingUMPUpdate ) => Promise /** * Locates the latest valid copy of a UMP token (including its outpoint) * based on the presentation key hash. * * @param hash The hash of the presentation key. * @returns The UMP token if found; otherwise, undefined. * @throws Implementations should throw when no verified token or clean empty response is available. */ findByPresentationKeyHash: (hash: number[], options?: UMPTokenLookupOptions) => Promise /** * Locates the latest valid copy of a UMP token (including its outpoint) * based on the recovery key hash. * * @param hash The hash of the recovery key. * @returns The UMP token if found; otherwise, undefined. * @throws Implementations should throw when no verified token or clean empty response is available. */ findByRecoveryKeyHash: (hash: number[], options?: UMPTokenLookupOptions) => Promise /** * Creates (and optionally consumes the previous version of) a UMP token on-chain. * * @param wallet The wallet that might be used to create a new token (MUST be operating under the DEFAULT profile). * @param adminOriginator The domain name of the administrative originator. * @param token The new UMP token to create. * @param oldTokenToConsume If provided, the old token that must be consumed in the same transaction. * @returns The newly created outpoint. */ buildAndSend: ( wallet: WalletInterface, // This wallet MUST be the one built for the default profile adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken, checkpoint?: UMPActionCheckpoint ) => Promise } export interface UMPTokenLookupOptions { /** * WAB-administered lineage anchor for competing verified matching tokens. * A proven update that consumes the pin supersedes it. An absent pin has * no effect unless its authenticated same-identity ancestry is available. */ pinnedOutpoint?: OutpointString } export interface UMPTokenLookupDiagnostics { hostCount: number completedHosts: number successfulHosts: number emptyHosts: number failedHosts: number rejectedHosts: number freeformHosts: number outputCount: number correlationId?: string } export type UMPTokenLookupFailureReason = 'lookup-unavailable' | 'lookup-incomplete' | 'token-malformed' | 'token-ambiguous' /** * Raised when a UMP lookup yields neither a verified token nor a clean empty response. * * Callers must offer retry/recovery rather than treating this error as a new * account. Diagnostics contain counts only and never hashes, keys, or tokens. */ export class UMPTokenLookupError extends Error { readonly code = 'WERR_UMP_LOOKUP_INDETERMINATE' constructor( public readonly reason: UMPTokenLookupFailureReason, public readonly diagnostics: UMPTokenLookupDiagnostics, options?: { cause?: unknown } ) { super('Unable to determine whether the wallet account already exists. Retry or use account recovery.', options) this.name = 'UMPTokenLookupError' } } /** * @class OverlayUMPTokenInteractor * * A concrete implementation of the UMPTokenInteractor interface that interacts * with Overlay Services and the UMP (User Management Protocol) topic. This class * is responsible for: * * 1) Locating UMP tokens via overlay lookups (ls_users). * 2) Creating and publishing new or updated UMP token outputs on-chain under * the "tm_users" topic. * 3) Consuming (spending) an old token if provided. */ export class OverlayUMPTokenInteractor implements UMPTokenInteractor { readonly checkpointVersion = 1 as const /** * A `LookupResolver` instance used to query overlay networks. */ private readonly resolver: LookupResolver /** * A SHIP broadcaster that can be used to publish updated UMP tokens * under the `tm_users` topic to overlay service peers. */ private readonly broadcaster: SHIPBroadcaster private readonly telemetry: Telemetry /** * Construct a new OverlayUMPTokenInteractor. * * @param resolver A LookupResolver instance for performing overlay queries (ls_users). * @param broadcaster A SHIPBroadcaster instance for sharing new or updated tokens across the `tm_users` overlay. */ constructor( resolver: LookupResolver = new LookupResolver(), broadcaster: SHIPBroadcaster = new SHIPBroadcaster(['tm_users']), telemetry?: TelemetryConfig ) { this.resolver = resolver this.broadcaster = broadcaster this.telemetry = new Telemetry(telemetry) } /** * Finds a UMP token on-chain by the given presentation key hash, if it exists. * Uses the ls_users overlay service to perform the lookup. * * @param hash The 32-byte SHA-256 hash of the presentation key. * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined. */ public findByPresentationKeyHash(hash: number[], options?: UMPTokenLookupOptions): Promise { return promiseFromSync(() => { return this.findToken( { service: 'ls_users', query: { presentationHash: toHex(hash) } }, 'presentation', options ) }) } /** * Finds a UMP token on-chain by the given recovery key hash, if it exists. * Uses the ls_users overlay service to perform the lookup. * * @param hash The 32-byte SHA-256 hash of the recovery key. * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined. */ public findByRecoveryKeyHash(hash: number[], options?: UMPTokenLookupOptions): Promise { return promiseFromSync(() => { return this.findToken( { service: 'ls_users', query: { recoveryHash: toHex(hash) } }, 'recovery', options ) }) } private async findToken( question: { service: string; query: Record }, lookupKind: 'presentation' | 'recovery', options?: UMPTokenLookupOptions ): Promise { const correlationId = this.telemetry.enabled === true ? this.telemetry.createCorrelationId() : undefined const startedAt = Date.now() this.telemetry.capture({ name: 'wallet-toolbox.ump.lookup.started', component: 'wallet-toolbox.ump', severity: 'debug', correlationId, attributes: { lookupKind } }) let resolution: LookupResolution try { resolution = await this.resolver.queryDetailed(question, undefined, { waitForAllHosts: true, correlationId }) } catch (error) { const diagnostics = this.emptyStats(correlationId) this.lookupFailed(lookupKind, 'lookup-unavailable', diagnostics, startedAt, error) throw new UMPTokenLookupError('lookup-unavailable', diagnostics, { cause: error }) } const diagnostics = this.diagnosticsFor(resolution) const tokens = this.parseLookupAnswers(resolution.answer) const expectedHash = question.query[lookupKind === 'presentation' ? 'presentationHash' : 'recoveryHash'].toLowerCase() const matchingTokens = tokens.filter( token => toHex(lookupKind === 'presentation' ? token.presentationHash : token.recoveryHash).toLowerCase() === expectedHash ) // A verified token is positive account-existence evidence. Empty, malformed, // rejected, or unavailable peers cannot override it. The resolver de-duplicates // identical outputs, so multiple matching tokens represent distinct records. // Competing records are usually stale renditions: a token update spends its // predecessor's outpoint, so the newest rendition is the sole candidate not // spent by another candidate's transaction history. Only unrelated (forked) // tokens remain indeterminate. if (matchingTokens.length > 1) { const pinnedLineage = await this.findPinnedLineage( matchingTokens, resolution.answer.outputs, options?.pinnedOutpoint ) const newest = this.resolveNewestToken(pinnedLineage ?? matchingTokens, resolution.answer.outputs) if (newest != null) { this.lookupDone(lookupKind, 'found', diagnostics, startedAt, { supersededTokens: matchingTokens.length - 1 }) return newest } const pinned = pinnedLineage == null && options?.pinnedOutpoint ? matchingTokens.find(token => token.currentOutpoint === options.pinnedOutpoint) : undefined if (pinned != null) { this.lookupDone(lookupKind, 'found', diagnostics, startedAt) return pinned } const reason = 'token-ambiguous' this.lookupFailed(lookupKind, reason, diagnostics, startedAt) throw new UMPTokenLookupError(reason, diagnostics) } if (matchingTokens.length === 1) { this.lookupDone(lookupKind, 'found', diagnostics, startedAt) return matchingTokens[0] } // A clean empty response is sufficient negative evidence once no verified // token exists. Malformed outputs and failed peers are ignored so they cannot // deny onboarding by advertising corrupt data or remaining unavailable. if (resolution.progress.emptyHosts > 0) { this.lookupDone(lookupKind, 'not-found', diagnostics, startedAt) return undefined } const reason = resolution.answer.outputs.length > 0 ? 'token-malformed' : 'lookup-incomplete' this.lookupFailed(lookupKind, reason, diagnostics, startedAt) throw new UMPTokenLookupError(reason, diagnostics) } /** Keep a verified pin and its proven descendants together, excluding unrelated forks. */ private async findPinnedLineage( tokens: UMPToken[], outputs: LookupAnswer['outputs'], pinnedOutpoint?: OutpointString ): Promise { if (pinnedOutpoint == null) return undefined const candidates = new Map(tokens.map(token => [token.currentOutpoint, token])) const pinSource = candidates.has(pinnedOutpoint) ? this.findLookupTransaction(outputs, pinnedOutpoint) : undefined const relationships = await Promise.all( outputs.map(output => this.pinRelationship(output, candidates, pinnedOutpoint, pinSource)) ) const related = new Set() let anchorSeen = false for (const relationship of relationships) { if (relationship == null) continue anchorSeen = true if (relationship.selected) related.add(relationship.outpoint) } return anchorSeen ? tokens.filter(token => related.has(token.currentOutpoint as string)) : undefined } private async pinRelationship( output: LookupAnswer['outputs'][number], candidates: ReadonlyMap, pin: string, pinSource?: Transaction ): Promise<{ outpoint: string; selected: boolean } | undefined> { try { const tx = this.readTokenHistory(output.beef) const outpoint = `${tx.id('hex')}.${output.outputIndex}` if (!candidates.has(outpoint)) return undefined if (outpoint === pin) return { outpoint, selected: true } const descent = this.descendsFromPin(tx, pin, pinSource) if (descent == null) return undefined return { outpoint, selected: descent === 'verified' && (await this.hasCompleteUpdateEvidence(tx)) } } catch { // A malformed copy cannot establish an anchor or hide a deeper copy. return undefined } } /** Preserve unmined funding-ancestry checks without adding a network dependency. */ private async hasCompleteUpdateEvidence(tx: Transaction): Promise { try { return await tx.verify('scripts only') } catch { // An input reference alone does not establish a usable token update. return false } } private descendsFromPin( tx: Transaction, pin: string, pinSource?: Transaction ): 'verified' | 'incomplete' | undefined { const pending = [tx] const visited = new Set() let incomplete = false while (pending.length > 0) { const current = pending.pop() as Transaction const txid = current.id('hex') if (visited.has(txid)) continue visited.add(txid) for (const [inputIndex] of current.inputs.entries()) { const step = this.pinInputDescent(current, inputIndex, pin, pinSource) if (step.descent === 'verified') return step.descent incomplete = incomplete || step.descent === 'incomplete' if (step.predecessor != null) pending.push(step.predecessor) } } return incomplete ? 'incomplete' : undefined } private pinInputDescent( tx: Transaction, inputIndex: number, pin: string, pinSource?: Transaction ): { descent?: 'verified' | 'incomplete'; predecessor?: Transaction } { const input = tx.inputs[inputIndex] const sourceTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex') const isPin = sourceTxid != null && `${sourceTxid}.${input.sourceOutputIndex}` === pin const source = input.sourceTransaction ?? (isPin ? pinSource : undefined) const refused = { descent: isPin ? ('incomplete' as const) : undefined } if (source == null || !this.isAuthenticatedUMPOutput(source.outputs[input.sourceOutputIndex])) return refused if (!this.verifyUMPSpend(tx, inputIndex, source)) return refused return isPin ? { descent: 'verified' } : { predecessor: source } } private isAuthenticatedUMPOutput(output: Transaction['outputs'][number] | undefined): boolean { if (output?.satoshis !== 1) return false try { const { fields } = decodeAuthenticatedUMPFields(output.lockingScript) return ( fields.length >= 11 && fields[6]?.length === 32 && fields[7]?.length === 32 && fields.slice(0, 11).every(field => field.length > 0 && field.length <= MAX_STATE_SNAPSHOT_BYTES) ) } catch { // A funding input or unauthenticated predecessor is not a UMP anchor. return false } } /** Check token-control continuity at every edge, including confirmed transactions. */ private verifyUMPSpend(tx: Transaction, inputIndex: number, source: Transaction): boolean { try { const input = tx.inputs[inputIndex] const sourceTxid = source.id('hex') if (input.unlockingScript == null || (input.sourceTXID != null && input.sourceTXID !== sourceTxid)) return false const output = source.outputs[input.sourceOutputIndex] return new Spend({ sourceTXID: sourceTxid, sourceOutputIndex: input.sourceOutputIndex, sourceSatoshis: output.satoshis ?? 0, lockingScript: output.lockingScript, transactionVersion: tx.version, otherInputs: tx.inputs.filter((_, index) => index !== inputIndex), unlockingScript: input.unlockingScript, inputSequence: input.sequence ?? 0xffffffff, inputIndex, outputs: tx.outputs, lockTime: tx.lockTime }).validate() } catch { return false } } private findLookupTransaction(outputs: LookupAnswer['outputs'], outpoint: string): Transaction | undefined { for (const output of outputs) { try { const tx = this.readTokenHistory(output.beef) if (`${tx.id('hex')}.${output.outputIndex}` === outpoint) return tx } catch { // A malformed copy does not hide another host's usable anchor. } } return undefined } /** Link explicit overlay history even when an ancestor already has a Merkle proof. */ private readTokenHistory(bytes: number[]): Transaction { const tx = Transaction.fromBEEF(bytes) const beef = Beef.fromBinary(bytes) const pending = [tx] const visited = new Set() while (pending.length > 0) { const current = pending.pop() as Transaction const txid = current.id('hex') if (visited.has(txid)) continue visited.add(txid) for (const input of current.inputs) { const sourceTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex') if (input.sourceTransaction == null && sourceTxid != null) { input.sourceTransaction = beef.findAtomicTransaction(sourceTxid) } if (input.sourceTransaction != null) pending.push(input.sourceTransaction) } } return tx } /** * Picks the newest rendition among distinct verified tokens, when possible. * * The on-chain UMP protocol expresses token updates by consumption: the * transaction creating a new rendition spends the previous rendition's * outpoint (there is no rendition counter field in the current format). * A candidate is therefore superseded when any other candidate's ancestry * (available from its BEEF) spends the candidate's outpoint. * * @returns The single unsuperseded candidate, or undefined when supersession * cannot be established for every stale candidate (e.g. forked tokens). */ private resolveNewestToken(matchingTokens: UMPToken[], outputs: LookupAnswer['outputs']): UMPToken | undefined { const candidates = new Map() for (const token of matchingTokens) { if (token.currentOutpoint == null) return undefined candidates.set(token.currentOutpoint, token) } // Hosts may serve the same token with different BEEF depth, so evidence // for a candidate is merged across every copy rather than first-wins: a // shallow copy must not mask the supersession proof a deeper copy carries. const evidenceByCandidate = new Map }>() for (const output of outputs) { try { const tx = this.readTokenHistory(output.beef) const outpoint = `${tx.id('hex')}.${output.outputIndex}` if (!candidates.has(outpoint)) continue const evidence = evidenceByCandidate.get(outpoint) ?? { txs: [], spent: new Set() } evidence.txs.push(tx) this.collectSpends(tx, evidence.spent, new Set()) evidenceByCandidate.set(outpoint, evidence) } catch { // Malformed outputs never produced candidates; nothing to correlate. } } // Without an evidence transaction for every candidate, an unexamined // candidate would trivially survive — refuse to guess. if (evidenceByCandidate.size !== candidates.size) return undefined const survivors = [...candidates.keys()].filter( outpoint => ![...evidenceByCandidate.entries()].some(([other, { spent }]) => other !== outpoint && spent.has(outpoint)) ) if (survivors.length === 1) return candidates.get(survivors[0]) // Forked candidates: no spend relationship connects them. Updating a token // requires unlocking its predecessor, so a candidate whose transaction // provably consumed a same-identity token demonstrates continuity of key // control; a freshly minted competitor (funding inputs only) is the anomaly // — typically a historical erroneous re-onboarding. Prefer the sole proven // continuation; anything less decisive stays indeterminate. const provenContinuations = survivors.filter(outpoint => { const evidence = evidenceByCandidate.get(outpoint) const token = candidates.get(outpoint) return evidence != null && token != null && evidence.txs.some(tx => this.consumesIdentity(tx, token)) }) if (provenContinuations.length !== 1) return undefined return candidates.get(provenContinuations[0]) } /** * Whether `tx` spends an input whose source output (available in the BEEF) * decodes as a UMP token sharing the candidate's presentation or recovery * hash — on-chain proof that the candidate is an update of a same-identity * predecessor rather than an independently minted token. */ private consumesIdentity(tx: Transaction, token: UMPToken): boolean { const presentationHash = toHex(token.presentationHash) const recoveryHash = toHex(token.recoveryHash) for (const input of tx.inputs) { const source = input.sourceTransaction if (source == null || input.sourceOutputIndex == null) continue const sourceOutput = source.outputs[input.sourceOutputIndex] if (sourceOutput == null) continue try { const { fields } = decodeAuthenticatedUMPFields(sourceOutput.lockingScript) if (fields.length < 11 || fields[6]?.length !== 32 || fields[7]?.length !== 32) continue if (toHex(fields[6]) === presentationHash || toHex(fields[7]) === recoveryHash) { return true } } catch { continue } } return false } /** * Accumulates every outpoint spent by `tx` and by the ancestor transactions * embedded in its BEEF, so supersession is detected even when intermediate * renditions are absent from the lookup answer. Iterative so arbitrarily * long update chains cannot exhaust the call stack. */ private collectSpends(tx: Transaction, spent: Set, visited: Set): void { const pending: Transaction[] = [tx] while (pending.length > 0) { const current = pending.pop() as Transaction const txid = current.id('hex') if (visited.has(txid)) continue visited.add(txid) for (const input of current.inputs) { const sourceTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex') if (sourceTxid == null || input.sourceOutputIndex == null) continue spent.add(`${sourceTxid}.${input.sourceOutputIndex}`) if (input.sourceTransaction != null) { pending.push(input.sourceTransaction) } } } } private emptyStats(correlationId?: string): UMPTokenLookupDiagnostics { return { hostCount: 0, completedHosts: 0, successfulHosts: 0, emptyHosts: 0, failedHosts: 0, rejectedHosts: 0, freeformHosts: 0, outputCount: 0, ...(correlationId !== undefined ? { correlationId } : {}) } } private diagnosticsFor(resolution: LookupResolution): UMPTokenLookupDiagnostics { const progress = resolution.progress return { hostCount: progress.hostCount, completedHosts: progress.completedHosts, successfulHosts: progress.successfulHosts, emptyHosts: progress.emptyHosts, failedHosts: progress.failedHosts, rejectedHosts: progress.rejectedHosts, freeformHosts: progress.freeformHosts, outputCount: resolution.answer.outputs.length, ...(progress.correlationId !== undefined ? { correlationId: progress.correlationId } : {}) } } private lookupAttrs(diagnostics: UMPTokenLookupDiagnostics): Record { return { hostCount: diagnostics.hostCount, completedHosts: diagnostics.completedHosts, successfulHosts: diagnostics.successfulHosts, emptyHosts: diagnostics.emptyHosts, failedHosts: diagnostics.failedHosts, rejectedHosts: diagnostics.rejectedHosts, freeformHosts: diagnostics.freeformHosts, outputCount: diagnostics.outputCount } } private lookupDone( lookupKind: 'presentation' | 'recovery', result: 'found' | 'not-found', diagnostics: UMPTokenLookupDiagnostics, startedAt: number, extraAttributes: Record = {} ): void { this.telemetry.capture({ name: 'wallet-toolbox.ump.lookup.completed', component: 'wallet-toolbox.ump', severity: 'info', correlationId: diagnostics.correlationId, attributes: { lookupKind, result, durationMs: Date.now() - startedAt, ...this.lookupAttrs(diagnostics), ...extraAttributes } }) } private lookupFailed( lookupKind: 'presentation' | 'recovery' | 'outpoint', reason: UMPTokenLookupFailureReason, diagnostics: UMPTokenLookupDiagnostics, startedAt: number, error?: unknown ): void { this.telemetry.capture({ name: 'wallet-toolbox.ump.lookup.indeterminate', component: 'wallet-toolbox.ump', severity: 'warn', correlationId: diagnostics.correlationId, attributes: { lookupKind, reason, durationMs: Date.now() - startedAt, ...this.lookupAttrs(diagnostics) }, error }) } /** * Creates or updates (replaces) a UMP token on-chain. If `oldTokenToConsume` is provided, * it is spent in the same transaction that creates the new token output. The new token is * then broadcast and published under the `tm_users` topic using a SHIP broadcast, ensuring * overlay participants see the updated token. * * @param wallet The wallet used to build and sign the transaction (MUST be operating under the DEFAULT profile). * @param adminOriginator The domain/FQDN of the administrative originator (wallet operator). * @param token The new UMPToken to create on-chain. * @param oldTokenToConsume Optionally, an existing token to consume/spend in the same transaction. * @returns The outpoint of the newly created UMP token (e.g. "abcd1234...ef.0"). */ public async buildAndSend( wallet: WalletInterface, // This wallet MUST be the one built for the default profile adminOriginator: OriginatorDomainNameStringUnder250Bytes, token: UMPToken, oldTokenToConsume?: UMPToken, checkpoint?: UMPActionCheckpoint ): Promise { // 1) Construct the data fields and PushDrop locking script for the new UMP token. const fields = this.tokenFields(token) const script = await new PushDrop(wallet, adminOriginator).lock( fields, [2, 'admin user management token'], '1', 'self', /* forSelf= */ true, /* includeSignature= */ true ) const tokenScript = script.toHex() const tokenOutput = [{ lockingScript: tokenScript, satoshis: 1, outputDescription: 'New UMP token output' }] // 2) Resolve the old-token input (if provided) and create the action. const { resolvedOldToken, inputToken } = await this.resolveOldInput(oldTokenToConsume) if (resolvedOldToken != null && inputToken != null) { await this.assertOwnedUMPInput(wallet, adminOriginator, resolvedOldToken, inputToken) } const inputs: CreateActionInput[] = resolvedOldToken?.currentOutpoint ? [ { outpoint: resolvedOldToken.currentOutpoint, unlockingScriptLength: 73, inputDescription: 'Consume old UMP token' } ] : [] const createArgs: CreateActionArgs = { description: resolvedOldToken == null ? 'Create new UMP token' : 'Renew UMP token (consume old, create new)', ...(checkpoint == null ? {} : { labels: [umpUpdateActionLabel(checkpoint.operationId)] }), inputs, outputs: tokenOutput, inputBEEF: inputToken?.beef, options: { randomizeOutputs: false, acceptDelayedBroadcast: false } } const inputSigners = Object.create(null) as NonNullable< NonNullable[2]>['inputSigners'] > if (resolvedOldToken?.currentOutpoint != null) { const unlocker = new PushDrop(wallet, adminOriginator).unlock([2, 'admin user management token'], '1', 'self') inputSigners[resolvedOldToken.currentOutpoint] = (transaction, inputIndex) => awaitFromSync(() => unlocker.sign(transaction, inputIndex)) } const operation = resolvedOldToken == null ? 'create' : 'renew' let transaction: Transaction try { transaction = await this.completeUMPAction(wallet, createArgs, inputSigners, adminOriginator, checkpoint) } catch (error) { this.telemetry.capture({ name: 'wallet-toolbox.ump.action.failed', component: 'wallet-toolbox.ump', severity: 'error', attributes: { operation, oldTokenInputRequired: resolvedOldToken != null }, error }) throw error } if (checkpoint != null) { const outpoint = this.umpTransactionOutpoint(transaction, tokenScript) await checkpoint.onCompleted(transaction.toAtomicBEEF(), outpoint) await this.sendSignedUMPAction(wallet, adminOriginator, transaction) } return await this.broadcastUMPTransaction(transaction, tokenScript, operation) } /** Assembles the ordered number[][] fields array from a UMPToken. */ private tokenFields(token: UMPToken): number[][] { const fields: number[][] = [] fields[0] = token.passwordSalt fields[1] = token.passwordPresentationPrimary fields[2] = token.passwordRecoveryPrimary fields[3] = token.presentationRecoveryPrimary fields[4] = token.passwordPrimaryPrivileged fields[5] = token.presentationRecoveryPrivileged fields[6] = token.presentationHash fields[7] = token.recoveryHash fields[8] = token.presentationKeyEncrypted fields[9] = token.passwordKeyEncrypted fields[10] = token.recoveryKeyEncrypted if (token.profilesEncrypted != null) fields[11] = token.profilesEncrypted if (token.umpVersion === 3 && token.passwordKdf != null) { const vi = token.profilesEncrypted == null ? 11 : 12 fields[vi] = [token.umpVersion] fields[vi + 1] = toArray(token.passwordKdf.algorithm, 'utf8') const kdfParams: Record = { iterations: token.passwordKdf.iterations } if (token.passwordKdf.memoryKiB !== undefined) kdfParams.memoryKiB = token.passwordKdf.memoryKiB if (token.passwordKdf.parallelism !== undefined) kdfParams.parallelism = token.passwordKdf.parallelism if (token.passwordKdf.hashLength !== undefined) kdfParams.hashLength = token.passwordKdf.hashLength fields[vi + 2] = toArray(JSON.stringify(kdfParams), 'utf8') } return fields } /** Looks up the old token on the overlay; returns undefined resolved token if not found. */ private async resolveOldInput( oldTokenToConsume?: UMPToken ): Promise<{ resolvedOldToken?: UMPToken; inputToken?: { beef: number[]; outputIndex: number } }> { if (!oldTokenToConsume?.currentOutpoint) return { resolvedOldToken: undefined, inputToken: undefined } const inputToken = await this.findByOutpoint(oldTokenToConsume.currentOutpoint) if (inputToken == null) { throw new Error('Previous UMP token unavailable; update refused.') } return { resolvedOldToken: oldTokenToConsume, inputToken } } /** Proves the exact predecessor is an authenticated token controlled by this wallet. */ private async assertOwnedUMPInput( wallet: Pick, adminOriginator: OriginatorDomainNameStringUnder250Bytes, oldToken: UMPToken, inputToken: { beef: number[]; outputIndex: number } ): Promise { const transaction = Transaction.fromBEEF(inputToken.beef) const sourceOutput = transaction.outputs[inputToken.outputIndex] if (sourceOutput == null) throw new Error('Previous UMP token source output is missing.') const decoded = decodeAuthenticatedUMPFields(sourceOutput.lockingScript) if ( decoded.fields[6]?.length !== 32 || decoded.fields[7]?.length !== 32 || toHex(decoded.fields[6]) !== toHex(oldToken.presentationHash) || toHex(decoded.fields[7]) !== toHex(oldToken.recoveryHash) ) { throw new Error('Previous UMP token identity does not match its authenticated source.') } const { publicKey } = await wallet.getPublicKey( { protocolID: [2, 'admin user management token'], keyID: '1', counterparty: 'self', forSelf: true }, adminOriginator ) if (publicKey.toLowerCase() !== decoded.lockingPublicKey.toString().toLowerCase()) { throw new Error('Previous UMP token is not controlled by this wallet.') } } /** Completes an action only after exact request, input, output, and final-transaction binding. */ private completeUMPAction( wallet: WalletInterface, createArgs: CreateActionArgs, inputSigners: NonNullable[2]>['inputSigners'], adminOriginator: OriginatorDomainNameStringUnder250Bytes, checkpoint?: UMPActionCheckpoint ): Promise { if (checkpoint == null) return awaitFromSync(() => completeBoundAction(wallet, createArgs, { inputSigners }, adminOriginator)) // Set noSend at signing so Toolbox plans and persists the action through its ordinary storage path. // noSend at creation can instead open an in-memory batch that would be lost on restart. const signAction: WalletInterface['signAction'] = async (args, originator) => { // Planning and input binding can fail before the wallet is asked to sign. await checkpoint.onStarting?.() return await wallet.signAction({ ...args, options: { ...args.options, noSend: true } }, originator) } const stagingWallet = new Proxy(wallet, { get(target, property) { if (property === 'signAction') return signAction const value: unknown = Reflect.get(target, property) return typeof value === 'function' ? value.bind(target) : value } }) return awaitFromSync(() => completeBoundAction(stagingWallet, createArgs, { inputSigners }, adminOriginator)) } private async sendSignedUMPAction( wallet: WalletInterface, adminOriginator: string, transaction: Transaction ): Promise { const txid = transaction.id('hex') const result = await wallet.createAction( { description: 'Broadcast signed UMP token', options: { sendWith: [txid], acceptDelayedBroadcast: false } }, adminOriginator ) if (result.sendWithResults?.find(item => item.txid === txid)?.status !== 'unproven') { throw new Error('Wallet did not confirm submission of the signed UMP update.') } } /** Verifies authenticated token fields and root ownership without constructing a wallet. */ async verifyToken( wallet: Pick, adminOriginator: string, token: UMPToken ): Promise { if (token.currentOutpoint == null) throw new Error('Discovered UMP token has no outpoint.') const input = await this.findByOutpoint(token.currentOutpoint) if (input == null) throw new Error('Discovered UMP token proof is unavailable.') await this.assertOwnedUMPInput(wallet, adminOriginator, token, input) } /** Read and authenticate the original receipt from locally readable Toolbox wallet storage. */ async recoverCheckpoint( wallet: WalletInterface, adminOriginator: string, token: UMPToken, previousToken: UMPToken, checkpoint: PendingUMPUpdate ): Promise { validatePendingUMPUpdate(checkpoint) const bytes = await readUMPActionReceipt(wallet, checkpoint.operationId, adminOriginator) if (bytes == null) return undefined if (bytes.length > MAX_STATE_SNAPSHOT_BYTES) throw new Error('Retained UMP receipt is too large.') const transaction = Transaction.fromAtomicBEEF(bytes) const expected = JSON.stringify(this.tokenFields(token)) const outputs = transaction.outputs.flatMap((output, index) => { if (output.satoshis !== 1) return [] try { return JSON.stringify(decodeAuthenticatedUMPFields(output.lockingScript).fields) === expected ? [index] : [] } catch { return [] } }) if (outputs.length !== 1) throw new Error('Retained wallet action has no unique intended UMP output.') const outpoint = `${transaction.id('hex')}.${outputs[0]}` await this.verifyCheckpoint(wallet, adminOriginator, token, previousToken, { ...checkpoint, stage: 'signed', transaction: bytes, outpoint }) return { transaction: bytes, outpoint } } /** Re-publishes the exact signed update. */ async publishCheckpoint( wallet: WalletInterface, adminOriginator: string, token: UMPToken, previousToken: UMPToken, checkpoint: PendingUMPUpdate ): Promise { const transaction = await this.verifyCheckpoint(wallet, adminOriginator, token, previousToken, checkpoint) const outputIndex = Number(checkpoint.outpoint!.split('.')[1]) await this.sendSignedUMPAction(wallet, adminOriginator, transaction) return await this.broadcastUMPTransaction( transaction, transaction.outputs[outputIndex].lockingScript.toHex(), 'renew' ) } private async verifyCheckpoint( wallet: WalletInterface, adminOriginator: string, token: UMPToken, previousToken: UMPToken, checkpoint: PendingUMPUpdate ): Promise { validatePendingUMPUpdate(checkpoint) if (checkpoint.transaction == null || previousToken.currentOutpoint == null) throw new Error('The original wallet action needs reconciliation before publication.') const transaction = Transaction.fromAtomicBEEF(checkpoint.transaction) const outputIndex = Number(checkpoint.outpoint?.split('.')[1]) const output = transaction.outputs[outputIndex] if (output == null || `${transaction.id('hex')}.${outputIndex}` !== checkpoint.outpoint) throw new Error('Pending UMP transaction identity mismatch.') const decoded = decodeAuthenticatedUMPFields(output.lockingScript) const expectedFields = this.tokenFields(token) if (JSON.stringify(decoded.fields) !== JSON.stringify(expectedFields)) throw new Error('Pending UMP transaction does not contain the intended update.') const publicKey = ( await wallet.getPublicKey( { protocolID: [2, 'admin user management token'], keyID: '1', counterparty: 'self', forSelf: true }, adminOriginator ) ).publicKey if (decoded.lockingPublicKey.toString().toLowerCase() !== publicKey.toLowerCase()) throw new Error('Pending UMP transaction is not owned by this wallet.') const inputs = transaction.inputs.filter( input => `${input.sourceTXID ?? input.sourceTransaction?.id('hex')}.${input.sourceOutputIndex}` === previousToken.currentOutpoint ) if (inputs.length !== 1) throw new Error('Pending UMP transaction must consume its exact predecessor.') const tokenScript = output.lockingScript.toHex() if (this.umpTransactionOutpoint(transaction, tokenScript) !== checkpoint.outpoint) throw new Error('Pending UMP transaction output mismatch.') return transaction } private umpTransactionOutpoint(transaction: Transaction, tokenScript: string): string { const matches = transaction.outputs.flatMap((output, index) => output.satoshis === 1 && output.lockingScript.toHex().toLowerCase() === tokenScript.toLowerCase() ? [index] : [] ) if (matches.length !== 1) throw new Error('Final UMP transaction must contain exactly one requested token output.') return `${transaction.id('hex')}.${matches[0]}` } private async broadcastUMPTransaction( transaction: Transaction, tokenScript: string, operation: 'renew' | 'create' ): Promise { const normalizedScript = tokenScript.toLowerCase() const matchingOutputs = transaction.outputs.flatMap((output, index) => output.satoshis === 1 && output.lockingScript.toHex().toLowerCase() === normalizedScript ? [index] : [] ) if (matchingOutputs.length !== 1) { throw new Error('Final UMP transaction must contain exactly one requested token output.') } const txid = transaction.id('hex') const result = await this.broadcaster.broadcast(transaction) this.assertBroadcast(result, operation, txid) return `${txid}.${matchingOutputs[0]}` } private assertBroadcast( result: Awaited>, operation: 'renew' | 'create', expectedTxid: string ): void { const succeeded = result.status === 'success' && result.txid.toLowerCase() === expectedTxid.toLowerCase() this.telemetry.capture({ name: succeeded ? 'wallet-toolbox.ump.broadcast.completed' : 'wallet-toolbox.ump.broadcast.failed', component: 'wallet-toolbox.ump', severity: succeeded ? 'info' : 'error', attributes: { operation, outcome: result.status, ...(result.status === 'error' ? { code: result.code } : {}) } }) if (!succeeded) { const reason = result.status === 'error' ? result.code : 'transaction ID mismatch' throw new Error(`UMP token broadcast failed (${reason}).`) } } /** * Attempts to parse a LookupAnswer from the UMP lookup service. If successful, * extracts the token fields from the resulting transaction and constructs * a UMPToken object. * * @param answer The LookupAnswer returned by a query to ls_users. * @returns The parsed UMPToken or `undefined` if none found/decodable. */ private parseLookupAnswer(answer: LookupAnswer): UMPToken | undefined { return this.parseLookupAnswers(answer)[0] } private parseLookupAnswers(answer: LookupAnswer): UMPToken[] { if (answer.type !== 'output-list' || answer.outputs.length === 0) return [] const tokens: UMPToken[] = [] for (const output of answer.outputs) { const token = this.parseOutput(output) if (token != null) tokens.push(token) } return tokens } private parseOutput(output: LookupAnswer['outputs'][number]): UMPToken | undefined { try { const tx = Transaction.fromBEEF(output.beef) const txOutput = tx.outputs[output.outputIndex] if (txOutput == null) return undefined const { fields: protocolFields } = decodeAuthenticatedUMPFields(txOutput.lockingScript) if ( protocolFields.length < 11 || protocolFields.slice(0, 11).some(field => field.length === 0 || field.length > MAX_STATE_SNAPSHOT_BYTES) ) { return undefined } const kdfVersionFieldIndex = findKdfVersionFieldIndex(protocolFields) const token: UMPToken = { passwordSalt: protocolFields[0], passwordPresentationPrimary: protocolFields[1], passwordRecoveryPrimary: protocolFields[2], presentationRecoveryPrimary: protocolFields[3], passwordPrimaryPrivileged: protocolFields[4], presentationRecoveryPrivileged: protocolFields[5], presentationHash: protocolFields[6], recoveryHash: protocolFields[7], presentationKeyEncrypted: protocolFields[8], passwordKeyEncrypted: protocolFields[9], recoveryKeyEncrypted: protocolFields[10], currentOutpoint: `${tx.id('hex')}.${output.outputIndex}` } if (token.presentationHash.length !== 32 || token.recoveryHash.length !== 32) return undefined if (!addProfilesField(token, protocolFields, kdfVersionFieldIndex)) return undefined if (!addPasswordKdf(token, protocolFields, kdfVersionFieldIndex)) return undefined return token } catch { return undefined } } /** * Finds by outpoint for unlocking / spending previous tokens. * @param outpoint The outpoint we are searching by * @returns The result so that we can use it to unlock the transaction */ private async findByOutpoint(outpoint: string): Promise<{ beef: number[]; outputIndex: number } | undefined> { const correlationId = this.telemetry.enabled === true ? this.telemetry.createCorrelationId() : undefined const startedAt = Date.now() const match = /^([0-9a-f]{64})\.(0|[1-9]\d*)$/i.exec(outpoint) const requestedOutputIndex = match == null ? Number.NaN : Number(match[2]) if (match == null || !Number.isSafeInteger(requestedOutputIndex) || requestedOutputIndex > 0xffffffff) { const diagnostics = this.emptyStats(correlationId) this.lookupFailed('outpoint', 'token-malformed', diagnostics, startedAt) throw new UMPTokenLookupError('token-malformed', diagnostics) } const normalizedOutpoint = `${match[1].toLowerCase()}.${requestedOutputIndex}` let resolution: LookupResolution try { resolution = await this.resolver.queryDetailed( { service: 'ls_users', query: { outpoint } }, undefined, { waitForAllHosts: true, correlationId } ) } catch (error) { const diagnostics = this.emptyStats(correlationId) this.lookupFailed('outpoint', 'lookup-unavailable', diagnostics, startedAt, error) throw new UMPTokenLookupError('lookup-unavailable', diagnostics, { cause: error }) } if (resolution.answer.outputs.length === 0) { const p = resolution.progress if (p.emptyHosts === 0) { const diagnostics = this.diagnosticsFor(resolution) this.lookupFailed('outpoint', 'lookup-incomplete', diagnostics, startedAt) throw new UMPTokenLookupError('lookup-incomplete', diagnostics) } return undefined } const diagnostics = this.diagnosticsFor(resolution) const matchingOutputs: Array<{ beef: number[]; outputIndex: number }> = [] try { for (const output of resolution.answer.outputs) { if (!Number.isSafeInteger(output.outputIndex) || output.outputIndex < 0 || output.outputIndex > 0xffffffff) { throw new Error('UMP lookup returned an invalid output index') } const transaction = Transaction.fromBEEF(output.beef) if ( transaction.outputs[output.outputIndex] == null || `${transaction.id('hex')}.${output.outputIndex}` !== normalizedOutpoint ) { throw new Error('UMP lookup substituted the requested outpoint') } matchingOutputs.push(output) } } catch (error) { this.lookupFailed('outpoint', 'token-malformed', diagnostics, startedAt, error) throw new UMPTokenLookupError('token-malformed', diagnostics, { cause: error }) } if (matchingOutputs.length === 0) { this.lookupFailed('outpoint', 'token-malformed', diagnostics, startedAt) throw new UMPTokenLookupError('token-malformed', diagnostics) } matchingOutputs.sort((left, right) => right.beef.length - left.beef.length) return matchingOutputs[0] } } /** * Manages a "CWI-style" wallet that uses a UMP token and a * multi-key authentication scheme (password, presentation key, and recovery key), * supporting multiple user profiles under a single account. */ export class CWIStyleWalletManager implements WalletInterface { /** * Whether the user is currently authenticated (i.e., root keys are available). */ authenticated: boolean /** * Resolves once the optional snapshot (if provided to the constructor) has been * fully loaded and the wallet is ready to accept calls. * When no snapshot is provided this resolves immediately. * Await `ready` before calling wallet methods after constructing with a snapshot. */ get ready(): Promise { this._readyInit ??= this._init() return this._readyInit } private _readyInit?: Promise private readonly _initSnapshot?: number[] /** * The domain name of the administrative originator (wallet operator / vendor, or your own). */ private readonly adminOriginator: OriginatorDomainNameStringUnder250Bytes /** * The system that locates and publishes UMP tokens on-chain. */ private readonly UMPTokenInteractor: UMPTokenInteractor /** * Privacy-bounded diagnostic channel for wallet state transitions. */ protected readonly telemetry: Telemetry /** * A function called to persist the newly generated recovery key. * It should generally trigger a UI prompt where the user is asked to write it down. */ private readonly recoveryKeySaver: (key: number[]) => Promise /** * Asks the user to enter their password, for a given reason. * The test function can be used to see if the password is correct before resolving. * Only resolve with the correct password or reject with an error. * Resolving with an incorrect password will throw an error. */ private readonly passwordRetriever: ( reason: string, test: (passwordCandidate: string) => boolean | Promise ) => Promise /** * Optional function to fund a new Wallet after the new-user flow. */ private readonly newWalletFunder?: ( presentationKey: number[], wallet: WalletInterface, // The default profile wallet adminOriginator: OriginatorDomainNameStringUnder250Bytes ) => Promise /** Persists only encrypted UMP fields before an irreversible funding attempt. */ private readonly pendingRegistrationTokenSaver?: (token: number[]) => Promise /** * Builds the underlying wallet for a specific profile. */ private readonly walletBuilder: ( profilePrimaryKey: number[], profilePrivilegedKeyManager: PrivilegedKeyManager, profileId: number[] ) => Promise /** * Current mode of authentication. */ authenticationMode: 'presentation-key-and-password' | 'presentation-key-and-recovery-key' | 'recovery-key-and-password' = 'presentation-key-and-password' /** * Indicates new user or existing user flow. */ authenticationFlow: 'unknown' | 'new-user' | 'existing-user' = 'unknown' /** * The current UMP token in use. */ private currentUMPToken?: UMPToken private statePersistence?: WalletStatePersistence private pendingUMPUpdate?: PendingUMPUpdate private transitionTail: Promise = Promise.resolve() private stateGeneration = 0 private stateTransitionActive = false private stateTransitionGeneration = 0 private statePersistencePending = false private umpSyncStatus: 'unknown' | 'unchanged' | 'updated' | 'not-found' = 'unknown' /** Distinguishes authoritative absence from an unchanged verified lookup. */ getUMPTokenSyncStatus(): 'unknown' | 'unchanged' | 'updated' | 'not-found' { return this.umpSyncStatus } /** Attach an awaited device store before authentication. Never log its checkpoint payloads. */ setStatePersistence(persistence: WalletStatePersistence): void { if (this.statePersistence != null && this.statePersistence !== persistence) throw new Error('Wallet state persistence is already attached to this manager.') this.statePersistence = persistence } /** Restore a retained checkpoint only after restoring/authenticating its original account. */ loadPendingUMPUpdate(checkpoint: PendingUMPUpdate): void { if (this.statePersistence == null) throw new Error('Attach durable wallet state before loading a pending update.') validatePendingUMPUpdate(checkpoint) if ( this.rootPrimaryKey == null || new PrivateKey(this.rootPrimaryKey).toPublicKey().toString() !== checkpoint.rootIdentityKey ) throw new Error('Pending wallet update belongs to another account.') this.pendingUMPUpdate = { ...checkpoint, previousSnapshot: [...checkpoint.previousSnapshot], proposedToken: [...checkpoint.proposedToken], activeProfileId: [...checkpoint.activeProfileId], ...(checkpoint.transaction == null ? {} : { transaction: [...checkpoint.transaction] }) } } private runStateTransition(operation: () => Promise, recovery = false): Promise { if (this.statePersistence == null) return operation() const generation = this.stateGeneration const pending = this.transitionTail .catch(() => {}) .then(async () => { if (generation !== this.stateGeneration) throw new Error('Wallet session changed before the operation started.') if (!recovery && this.pendingUMPUpdate != null) throw new WalletStateTransitionError(this.pendingUMPUpdate.stage, undefined) this.stateTransitionActive = true this.stateTransitionGeneration = generation try { const result = await operation() this.assertTransitionCurrent() return result } catch (error) { if (this.pendingUMPUpdate != null && !(error instanceof WalletStateTransitionError)) throw new WalletStateTransitionError(this.pendingUMPUpdate.stage, error) throw error } finally { this.stateTransitionActive = false } }) this.transitionTail = pending return pending } private assertTransitionCurrent(): void { if ( this.statePersistence != null && this.stateTransitionActive && this.stateTransitionGeneration !== this.stateGeneration ) throw new Error('Wallet session changed during the state transition.') } private async persistState(profileId = this.activeProfileId): Promise { if (this.statePersistence == null) return this.assertTransitionCurrent() const snapshot = this.saveSnapshot() // Snapshot v2 deliberately keeps the device selection outside its payload. snapshot.splice(33, 16, ...profileId) try { await this.statePersistence.saveSnapshot(snapshot) this.assertTransitionCurrent() this.statePersistencePending = false } catch (error) { this.statePersistencePending = true throw new WalletStateTransitionError('persistence', error) } } private pendingUpdateRoot(pending: PendingUMPUpdate): number[] { if ( this.rootPrimaryKey == null || !this.authenticated || new PrivateKey(this.rootPrimaryKey).toPublicKey().toString() !== pending.rootIdentityKey ) throw new Error('Pending wallet update belongs to another account.') return this.rootPrimaryKey } /** Reconcile or re-publish the original update. Never constructs a replacement action. */ recoverPendingUMPUpdate(): Promise { return this.runStateTransition(async () => { const pending = this.pendingUMPUpdate if (pending == null) return validatePendingUMPUpdate(pending) const authenticatedRoot = this.pendingUpdateRoot(pending) if (pending.stage === 'prepared') { await this.statePersistence?.savePendingUpdate(null) this.pendingUMPUpdate = undefined return } const token = this.deserializeUMPToken(pending.proposedToken, true) const savedReader = new Reader(pending.previousSnapshot) const version = savedReader.readUInt8() if (version !== 2) throw new Error('Pending wallet update requires its original snapshot format.') const key = savedReader.read(32) savedReader.read(16) const payload = new Reader(new SymmetricKey(key).decrypt(savedReader.read()) as number[]) const root = payload.read(32) if (toHex(root) !== toHex(authenticatedRoot)) throw new Error('Pending wallet update root mismatch.') const previousToken = this.deserializeUMPToken(payload.read(payload.readVarIntNumStrict(false))) if (pending.transaction != null) { // A failed receipt write leaves the signed transaction in memory. Repair its durable copy before sending it. await this.statePersistence?.savePendingUpdate(pending) this.assertTransitionCurrent() } const outpoint = await this.resolvePendingUpdateOutpoint(root, pending, token, previousToken) this.assertTransitionCurrent() token.currentOutpoint = outpoint this.currentUMPToken = token await this.setupRoot(root) await this.activateProfile(pending.activeProfileId) await this.persistState() await this.statePersistence?.savePendingUpdate(null) this.pendingUMPUpdate = undefined }, true) } private async resolvePendingUpdateOutpoint( root: number[], pending: PendingUMPUpdate, token: UMPToken, previousToken: UMPToken ): Promise { const options = { pinnedOutpoint: previousToken.currentOutpoint } const refreshed = (await this.UMPTokenInteractor.findByPresentationKeyHash(token.presentationHash, options)) ?? (await this.UMPTokenInteractor.findByRecoveryKeyHash(token.recoveryHash, options)) const sameFields = (candidate: UMPToken) => toHex(this.serializeUMPToken({ ...candidate, currentOutpoint: '' }, true)) === toHex(pending.proposedToken) if (refreshed != null && sameFields(refreshed) && refreshed.currentOutpoint != null) { if (pending.outpoint != null && pending.outpoint !== refreshed.currentOutpoint) throw new Error('Discovered update does not match the original signed transaction.') await this.UMPTokenInteractor.verifyToken?.( new ProtoWallet(new PrivateKey(root)), this.adminOriginator, refreshed ) return refreshed.currentOutpoint } else { if (refreshed != null && refreshed.currentOutpoint !== previousToken.currentOutpoint) throw new Error('A different account update must be reconciled before continuing.') const publish = this.UMPTokenInteractor.publishCheckpoint if (publish == null) throw new WalletStateTransitionError(pending.stage, undefined) const selected = [...this.activeProfileId] await this.activateProfile(DEFAULT_PROFILE_ID) try { const wallet = this.underlying! const signed = pending.transaction == null ? await this.recoverOriginalUMPReceipt(wallet, token, previousToken, pending) : pending return await publish.call(this.UMPTokenInteractor, wallet, this.adminOriginator, token, previousToken, signed) } catch (error) { await this.activateProfile(selected).catch(() => {}) throw error } } } private async recoverOriginalUMPReceipt( wallet: WalletInterface, token: UMPToken, previousToken: UMPToken, pending: PendingUMPUpdate ): Promise { const receipt = await this.UMPTokenInteractor.recoverCheckpoint?.( wallet, this.adminOriginator, token, previousToken, pending ) this.assertTransitionCurrent() if (receipt == null) throw new WalletStateTransitionError(pending.stage, undefined) const signed = { ...pending, stage: 'signed' as const, transaction: receipt.transaction, outpoint: receipt.outpoint } validatePendingUMPUpdate(signed) await this.statePersistence?.savePendingUpdate(signed) this.assertTransitionCurrent() this.pendingUMPUpdate = signed return signed } /** Retry only local persistence. This never creates or publishes a transaction. */ retryStatePersistence(): Promise { return this.runStateTransition(async () => { await this.persistState() }, true) } /** Unpublished token retained through an interrupted new-user registration. */ private pendingRegistrationToken?: UMPToken /** * Temporarily retained presentation key. */ private presentationKey?: number[] /** * Temporarily retained recovery key. */ private recoveryKey?: number[] /** * The user's *root* primary key, derived from authentication factors. */ private rootPrimaryKey?: number[] /** * The currently active profile ID (null or DEFAULT_PROFILE_ID means default profile). */ private activeProfileId: number[] = DEFAULT_PROFILE_ID /** * List of loaded non-default profiles. */ private profiles: Profile[] = [] private readonly pendingProfileNames = new Set() /** * The underlying wallet instance for the *active* profile. */ private underlying?: WalletInterface /** * Privileged key manager associated with the *root* keys, aware of the active profile. */ private rootPrivilegedKeyManager?: PrivilegedKeyManager /** * KDF configuration for new UMP tokens. Defaults to Argon2id for v3 tokens. */ private readonly kdfConfig: Required /** * Constructs a new CWIStyleWalletManager. * * @param adminOriginator The domain name of the administrative originator. * @param walletBuilder A function that can build an underlying wallet instance for a profile. * @param interactor An instance of UMPTokenInteractor. * @param recoveryKeySaver A function to persist a new recovery key. * @param passwordRetriever A function to request the user's password. * @param newWalletFunder Optional function to fund a new wallet. * @param stateSnapshot Optional previously saved state snapshot. * @param kdfConfig Optional KDF configuration for new UMP tokens. * @param pendingRegistrationTokenSaver Optional durable store for an unpublished UMP token. */ constructor( ...[ adminOriginator, walletBuilder, interactor, recoveryKeySaver, passwordRetriever, newWalletFunder, stateSnapshot, kdfConfig, telemetry, pendingRegistrationTokenSaver ]: [ adminOriginator: OriginatorDomainNameStringUnder250Bytes, walletBuilder: ( profilePrimaryKey: number[], profilePrivilegedKeyManager: PrivilegedKeyManager, profileId: number[] ) => Promise, interactor: UMPTokenInteractor | undefined, recoveryKeySaver: (key: number[]) => Promise, passwordRetriever: ( reason: string, test: (passwordCandidate: string) => boolean | Promise ) => Promise, newWalletFunder?: ( presentationKey: number[], wallet: WalletInterface, adminOriginator: OriginatorDomainNameStringUnder250Bytes ) => Promise, stateSnapshot?: number[], kdfConfig?: KdfConfig, telemetry?: TelemetryConfig, pendingRegistrationTokenSaver?: (token: number[]) => Promise ] ) { this.adminOriginator = adminOriginator this.walletBuilder = walletBuilder this.telemetry = new Telemetry(telemetry) this.UMPTokenInteractor = interactor ?? new OverlayUMPTokenInteractor(undefined, undefined, telemetry) this.recoveryKeySaver = recoveryKeySaver this.passwordRetriever = passwordRetriever this.authenticated = false this.newWalletFunder = newWalletFunder this.pendingRegistrationTokenSaver = pendingRegistrationTokenSaver // Initialize KDF config with Argon2id defaults for v3 tokens const kdfAlgorithm = kdfConfig?.algorithm ?? 'argon2id' this.kdfConfig = { algorithm: kdfAlgorithm, iterations: kdfConfig?.iterations ?? (kdfAlgorithm === 'argon2id' ? ARGON2ID_DEFAULT_ITERATIONS : PBKDF2_NUM_ROUNDS), memoryKiB: kdfConfig?.memoryKiB ?? ARGON2ID_DEFAULT_MEMORY_KIB, parallelism: kdfConfig?.parallelism ?? ARGON2ID_DEFAULT_PARALLELISM, hashLength: kdfConfig?.hashLength ?? ARGON2ID_DEFAULT_HASH_LENGTH } if (!isValidKdfConfig(this.kdfConfig)) { throw new Error('Unsupported or unsafe KDF configuration.') } // Store snapshot for lazy init; callers await ready before calling wallet methods. this._initSnapshot = stateSnapshot } private async _init(): Promise { if (this._initSnapshot !== undefined) { this.telemetry.capture({ name: 'wallet-toolbox.snapshot.initialization.started', component: CWI_COMPONENT, severity: 'debug' }) try { await this.loadSnapshot(this._initSnapshot) this.telemetry.capture({ name: 'wallet-toolbox.snapshot.initialization.completed', component: CWI_COMPONENT, severity: 'info' }) } catch (error) { this.telemetry.capture({ name: 'wallet-toolbox.snapshot.initialization.failed', component: CWI_COMPONENT, severity: 'error', error }) throw error } } } // --- Authentication Methods --- /** * Restores an unpublished UMP token before authentication. The token contains * an encrypted wallet root, but no plaintext root, snapshot key, or on-chain outpoint. */ loadPendingRegistrationToken(bytes: number[]): void { if (this.authenticated || this.authenticationFlow !== 'unknown' || this.currentUMPToken != null) { throw new Error('Pending registration token must be loaded before authentication.') } if ( !Array.isArray(bytes) || bytes.length === 0 || bytes.length > MAX_PENDING_REGISTRATION_TOKEN_BYTES || bytes.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255) ) { throw new Error('Pending registration token is invalid.') } try { const token = this.deserializeUMPToken(bytes, true) if ( token.currentOutpoint != null || token.umpVersion !== 3 || !isValidKdfConfig(token.passwordKdf) || token.profilesEncrypted != null || token.passwordSalt.length !== 32 || token.presentationHash.length !== 32 || token.recoveryHash.length !== 32 ) { throw new Error('Invalid unpublished token fields.') } this.pendingRegistrationToken = token } catch { throw new Error('Pending registration token is invalid.') } } public hasPendingRegistrationToken(): boolean { return this.pendingRegistrationToken != null } /** * Provides the presentation key. A WAB operator pin may be supplied by the * authentication manager; normal lookup and lineage resolution always run * before this ambiguity-only fallback. */ async providePresentationKey(key: number[], lookupOptions?: UMPTokenLookupOptions): Promise { if (this.authenticated) { throw new Error('User is already authenticated') } if (this.authenticationMode === 'recovery-key-and-password') { throw new Error('Presentation key is not needed in this mode') } if (key.length !== 32 || key.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) { throw new TypeError('Presentation key must contain exactly 32 bytes.') } this.authenticationFlow = 'unknown' const hash = sha256(key) const pendingTokenMatches = this.pendingRegistrationToken == null || toHex(this.pendingRegistrationToken.presentationHash) === toHex(hash) const startedAt = Date.now() this.telemetry.capture({ name: 'wallet-toolbox.authentication.account-lookup.started', component: CWI_COMPONENT, severity: 'debug', attributes: { lookupKind: 'presentation' } }) let token: UMPToken | undefined try { token = await this.UMPTokenInteractor.findByPresentationKeyHash(hash, lookupOptions) } catch (error) { this.telemetry.capture({ name: 'wallet-toolbox.authentication.account-lookup.failed', component: CWI_COMPONENT, severity: 'warn', attributes: { lookupKind: 'presentation', durationMs: Date.now() - startedAt }, error }) throw error } if (token == null) { // No token found -> New user if (!pendingTokenMatches) { throw new Error('Pending registration token belongs to another presentation key.') } this.authenticationFlow = 'new-user' this.presentationKey = key this.currentUMPToken = this.pendingRegistrationToken } else { // Found token -> existing user this.authenticationFlow = 'existing-user' this.presentationKey = key this.currentUMPToken = token this.clearPublishedPendingRegistration(token) } this.telemetry.capture({ name: 'wallet-toolbox.authentication.account-lookup.completed', component: CWI_COMPONENT, severity: 'info', attributes: { lookupKind: 'presentation', accountStatus: this.authenticationFlow, durationMs: Date.now() - startedAt } }) } /** * Provides the password. */ async providePassword(password: string): Promise { if (this.authenticated) throw new Error('User is already authenticated') if (this.authenticationMode === 'presentation-key-and-recovery-key') { throw new Error('Password is not needed in this mode') } if (this.authenticationFlow === 'unknown') { throw new Error('Determine account status with a presentation or recovery key before providing a password.') } if (this.authenticationFlow === 'existing-user') { await this.unlockExisting(password) } else { await this.createNewUser(password) } } /** Handles the password step for an existing user — derives keys, sets up infrastructure. */ private async unlockExisting(password: string): Promise { if (this.currentUMPToken == null) throw new Error('Provide presentation or recovery key first.') const derivedPasswordKey = await derivePasswordKey(this.currentUMPToken, toArray(password, 'utf8')) let rootPrimaryKey: number[] let rootPrivilegedKey: number[] | undefined if (this.authenticationMode === 'presentation-key-and-password') { if (this.presentationKey == null) throw new Error('No presentation key found!') rootPrimaryKey = new SymmetricKey(this.XOR(this.presentationKey, derivedPasswordKey)).decrypt( this.currentUMPToken.passwordPresentationPrimary ) as number[] } else { // 'recovery-key-and-password' if (this.recoveryKey == null) throw new Error('No recovery key found!') const primaryDecryptionKey = this.XOR(this.recoveryKey, derivedPasswordKey) rootPrimaryKey = new SymmetricKey(primaryDecryptionKey).decrypt( this.currentUMPToken.passwordRecoveryPrimary ) as number[] rootPrivilegedKey = new SymmetricKey(this.XOR(rootPrimaryKey, derivedPasswordKey)).decrypt( this.currentUMPToken.passwordPrimaryPrivileged ) as number[] } await this.setupRoot(rootPrimaryKey, rootPrivilegedKey) await this.switchProfile(this.activeProfileId) } /** Handles the password step for a new user — generates keys, builds UMP token, publishes on-chain. */ private async createNewUser(password: string): Promise { if (this.authenticationMode !== 'presentation-key-and-password') { throw new Error('New-user flow requires presentation key and password mode.') } if (this.presentationKey == null) throw new Error('No presentation key provided for new-user flow.') let newToken: UMPToken let rootPrimaryKey: number[] if (this.pendingRegistrationToken != null) { newToken = this.pendingRegistrationToken rootPrimaryKey = await this.unlockPendingRegistrationToken(newToken, this.presentationKey, password) } else { const generated = await this.buildPendingRegistrationToken(password, this.presentationKey) newToken = generated.token rootPrimaryKey = generated.rootPrimaryKey this.pendingRegistrationToken = newToken } this.currentUMPToken = newToken // The caller must durably store the same encrypted token before a faucet // output can be redeemed. Repeating the write also repairs a prior failed // persistence attempt before any retry reaches the funder. if (this.pendingRegistrationTokenSaver != null) { await this.pendingRegistrationTokenSaver(this.serializeUMPToken(newToken, true)) } await this.setupRoot(rootPrimaryKey, undefined, false) await this.activateProfile(DEFAULT_PROFILE_ID) // Fund the *default* wallet if funder provided if (this.newWalletFunder != null && this.underlying != null) { try { await this.newWalletFunder(this.presentationKey, this.underlying, this.adminOriginator) } catch (error) { this.telemetry.capture({ name: 'wallet-toolbox.authentication.new-wallet-funding.failed', component: CWI_COMPONENT, severity: 'error', error: new Error('New wallet funding failed.') }) const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to fund new wallet before publishing UMP token: ${message}`, { cause: error }) } } if (this.underlying == null) throw new Error('Default profile wallet not built before attempting to publish UMP token.') newToken.currentOutpoint = await this.UMPTokenInteractor.buildAndSend( this.underlying, this.adminOriginator, newToken ) this.pendingRegistrationToken = undefined this.authenticated = true } private async unlockPendingRegistrationToken( token: UMPToken, presentationKey: number[], password: string ): Promise { try { const passwordKey = await derivePasswordKey(token, toArray(password, 'utf8')) const rootPrimaryKey = new SymmetricKey(this.XOR(presentationKey, passwordKey)).decrypt( token.passwordPresentationPrimary ) as number[] if (rootPrimaryKey.length !== 32) throw new Error('Invalid root key length.') return rootPrimaryKey } catch { throw new Error('Pending registration token could not be unlocked with this password.') } } private async buildPendingRegistrationToken( password: string, presentationKey: number[] ): Promise<{ token: UMPToken; rootPrimaryKey: number[] }> { // Generate new keys/salt const recoveryKey = Random(32) await this.recoveryKeySaver(recoveryKey) const passwordSalt = Random(32) const passwordKey = await derivePasswordKey( { passwordSalt, passwordKdf: this.kdfConfig }, toArray(password, 'utf8') ) const rootPrimaryKey = Random(32) const rootPrivilegedKey = Random(32) // Build XOR-combined symmetric keys const presentationPassword = new SymmetricKey(this.XOR(presentationKey, passwordKey)) const presentationRecovery = new SymmetricKey(this.XOR(presentationKey, recoveryKey)) const recoveryPassword = new SymmetricKey(this.XOR(recoveryKey, passwordKey)) const primaryPassword = new SymmetricKey(this.XOR(rootPrimaryKey, passwordKey)) const tempPrivilegedKeyManager = new PrivilegedKeyManager(() => promiseFromSync(() => new PrivateKey(rootPrivilegedKey)) ) const wrapKey = async (plaintext: number[]): Promise => (await tempPrivilegedKeyManager.encrypt({ plaintext, protocolID: [2, 'admin key wrapping'], keyID: '1' })) .ciphertext // Build new UMP token (v3 with KDF metadata, no profiles initially) const token: UMPToken = { passwordSalt, passwordPresentationPrimary: presentationPassword.encrypt(rootPrimaryKey) as number[], passwordRecoveryPrimary: recoveryPassword.encrypt(rootPrimaryKey) as number[], presentationRecoveryPrimary: presentationRecovery.encrypt(rootPrimaryKey) as number[], passwordPrimaryPrivileged: primaryPassword.encrypt(rootPrivilegedKey) as number[], presentationRecoveryPrivileged: presentationRecovery.encrypt(rootPrivilegedKey) as number[], presentationHash: sha256(presentationKey), recoveryHash: sha256(recoveryKey), presentationKeyEncrypted: await wrapKey(presentationKey), passwordKeyEncrypted: await wrapKey(passwordKey), recoveryKeyEncrypted: await wrapKey(recoveryKey), profilesEncrypted: undefined, umpVersion: 3, passwordKdf: this.kdfConfig } return { token, rootPrimaryKey } } /** * Provides the recovery key. */ async provideRecoveryKey(recoveryKey: number[]): Promise { if (this.authenticated) { throw new Error('Already authenticated') } if (this.authenticationFlow === 'new-user' && this.authenticationMode !== 'recovery-key-and-password') { throw new Error('Do not submit recovery key in new-user flow') } if (this.authenticationMode === 'presentation-key-and-password') { throw new Error('No recovery key required in this mode') } if (recoveryKey.length !== 32 || recoveryKey.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) { throw new TypeError('Recovery key must contain exactly 32 bytes.') } if (this.authenticationMode === 'recovery-key-and-password') { // Wait for password const hash = sha256(recoveryKey) const token = await this.UMPTokenInteractor.findByRecoveryKeyHash(hash) if (token == null) throw new Error('No user found with this recovery key') this.authenticationFlow = 'existing-user' this.recoveryKey = recoveryKey this.currentUMPToken = token } else { // 'presentation-key-and-recovery-key' if (this.presentationKey == null) throw new Error('Provide the presentation key first') if (this.currentUMPToken == null) throw new Error('Current UMP token not found') const xorKey = this.XOR(this.presentationKey, recoveryKey) const rootPrimaryKey = new SymmetricKey(xorKey).decrypt( this.currentUMPToken.presentationRecoveryPrimary ) as number[] const rootPrivilegedKey = new SymmetricKey(xorKey).decrypt( this.currentUMPToken.presentationRecoveryPrivileged ) as number[] // Build root infrastructure, load profiles, switch to default await this.setupRoot(rootPrimaryKey, rootPrivilegedKey) await this.switchProfile(this.activeProfileId) } } // --- State Management Methods --- /** * Saves the current wallet state (root key, UMP token, active profile) into an encrypted snapshot. * Version 2 format: [1 byte version=2] + [32 byte snapshot key] + [16 byte activeProfileId] + [encrypted payload] * Encrypted Payload: [32 byte rootPrimaryKey] + [varint token length + serialized UMP token] * * @returns Encrypted snapshot bytes. */ saveSnapshot(): number[] { if (this.rootPrimaryKey == null || this.currentUMPToken == null) { throw new Error('No root primary key or current UMP token set') } const snapshotKey = Random(32) const snapshotPreimageWriter = new Writer() // Write root primary key snapshotPreimageWriter.write(this.rootPrimaryKey) // Write serialized UMP token (must have outpoint) if (!this.currentUMPToken.currentOutpoint) { throw new Error('UMP token cannot be saved without a current outpoint.') } const serializedToken = this.serializeUMPToken(this.currentUMPToken) snapshotPreimageWriter.writeVarIntNum(serializedToken.length) snapshotPreimageWriter.write(serializedToken) // Encrypt the payload const snapshotPreimage = snapshotPreimageWriter.toArray() const snapshotPayload = new SymmetricKey(snapshotKey).encrypt(snapshotPreimage) as number[] // Build final snapshot (Version 2) const snapshotWriter = new Writer() snapshotWriter.writeUInt8(2) // Version snapshotWriter.write(snapshotKey) snapshotWriter.write(this.activeProfileId) // Active profile ID snapshotWriter.write(snapshotPayload) // Encrypted data const snapshot = snapshotWriter.toArray() if (snapshot.length > MAX_STATE_SNAPSHOT_BYTES) { throw new Error('Snapshot exceeds the maximum supported size.') } this.telemetry.capture({ name: 'wallet-toolbox.snapshot.saved', component: CWI_COMPONENT, severity: 'info', attributes: { formatVersion: 2, profileCount: this.profiles.length } }) return snapshot } /** * Loads a previously saved state snapshot. Restores root key, UMP token, profiles, and active profile. * Handles Version 1 (legacy) and Version 2 formats. * * @param snapshot Encrypted snapshot bytes. */ async loadSnapshot(snapshot: number[]): Promise { return this.runStateTransition(() => this.restoreSnapshot(snapshot)) } private async restoreSnapshot(snapshot: number[]): Promise { const generation = this.stateGeneration try { if ( snapshot.length === 0 || snapshot.length > MAX_STATE_SNAPSHOT_BYTES || snapshot.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255) ) { throw new Error('Snapshot is empty, oversized, or contains invalid bytes.') } const reader = new Reader(snapshot) const version = reader.readUInt8() let snapshotKey: number[] let encryptedPayload: number[] let activeProfileId = DEFAULT_PROFILE_ID // Default for V1 if (version === 1) { snapshotKey = reader.read(32) encryptedPayload = reader.read() } else if (version === 2) { snapshotKey = reader.read(32) activeProfileId = reader.read(16) // Read active profile ID encryptedPayload = reader.read() } else { throw new Error(`Unsupported snapshot version: ${version}`) } // Decrypt payload const decryptedPayload = new SymmetricKey(snapshotKey).decrypt(encryptedPayload) as number[] const payloadReader = new Reader(decryptedPayload) // Read root primary key const rootPrimaryKey = payloadReader.read(32) // Read serialized UMP token const tokenLen = payloadReader.readVarIntNumStrict(false) const tokenBytes = payloadReader.read(tokenLen) const token = this.deserializeUMPToken(tokenBytes) // Assign loaded data this.currentUMPToken = token // Setup root infrastructure, load profiles, and switch to the loaded active profile await this.setupRoot(rootPrimaryKey) if (this.statePersistence == null) { await this.switchProfile(activeProfileId) } else { await this.activateProfile(activeProfileId) await this.persistState() } this.clearPublishedPendingRegistration(token) this.authenticationFlow = 'existing-user' // Loading implies existing user this.telemetry.capture({ name: 'wallet-toolbox.snapshot.loaded', component: CWI_COMPONENT, severity: 'info', attributes: { formatVersion: version, profileCount: this.profiles.length } }) } catch (error) { if (this.stateGeneration === generation) this.destroy() this.telemetry.capture({ name: 'wallet-toolbox.snapshot.load-failed', component: CWI_COMPONENT, severity: 'error', error }) const message = error instanceof Error ? error.message : 'Unknown error' throw new Error(`Failed to load snapshot: ${message}`, { cause: error }) } } async syncUMPToken(): Promise { return this.runStateTransition(async () => { if (!this.authenticated || this.currentUMPToken == null || this.rootPrimaryKey == null) { throw new Error('Wallet not authenticated or missing UMP token.') } this.umpSyncStatus = 'unknown' const generation = this.stateGeneration const currentToken = this.currentUMPToken const lookupOptions: [UMPTokenLookupOptions?] = this.statePersistence == null ? [] : [{ pinnedOutpoint: currentToken.currentOutpoint }] let refreshed: UMPToken | undefined if (currentToken.presentationHash && currentToken.presentationHash.length > 0) { refreshed = await this.UMPTokenInteractor.findByPresentationKeyHash( currentToken.presentationHash, ...lookupOptions ) } if (refreshed == null && currentToken.recoveryHash && currentToken.recoveryHash.length > 0) { refreshed = await this.UMPTokenInteractor.findByRecoveryKeyHash(currentToken.recoveryHash, ...lookupOptions) } this.assertTransitionCurrent() if (refreshed == null) { this.umpSyncStatus = 'not-found' return false } if ( refreshed.currentOutpoint && currentToken.currentOutpoint && refreshed.currentOutpoint === currentToken.currentOutpoint ) { this.umpSyncStatus = 'unchanged' return false } const root = this.rootPrimaryKey if (this.statePersistence == null) { this.currentUMPToken = refreshed await this.setupRoot(root) this.saveSnapshot() this.umpSyncStatus = 'updated' return true } await this.applyVerifiedUMPRefresh(root, currentToken, refreshed, generation) this.umpSyncStatus = 'updated' return true }) } private async applyVerifiedUMPRefresh( root: number[], currentToken: UMPToken, refreshed: UMPToken, generation: number ): Promise { await this.UMPTokenInteractor.verifyToken?.(new ProtoWallet(new PrivateKey(root)), this.adminOriginator, refreshed) if (generation !== this.stateGeneration) throw new Error('Wallet session changed during account verification.') const previousProfiles = this.profiles const previousRootManager = this.rootPrivilegedKeyManager const activeId = [...this.activeProfileId] this.currentUMPToken = refreshed try { await this.setupRoot(root) if (!activeId.every(byte => byte === 0) && !this.profiles.some(profile => toHex(profile.id) === toHex(activeId))) throw new WalletProfileUnavailableError() await this.activateProfile(activeId) } catch (error) { if (generation === this.stateGeneration) { this.currentUMPToken = currentToken this.profiles = previousProfiles this.rootPrivilegedKeyManager = previousRootManager } throw error } await this.persistState() } private clearPublishedPendingRegistration(token: UMPToken): void { // A conflicting wallet root can share the same presentation key; match the // encrypted root field before discarding the unpublished token. if ( this.pendingRegistrationToken != null && toHex(this.pendingRegistrationToken.presentationHash) === toHex(token.presentationHash) && toHex(this.pendingRegistrationToken.passwordPresentationPrimary) === toHex(token.passwordPresentationPrimary) ) { this.pendingRegistrationToken = undefined } } /** * Destroys the wallet state, clearing keys, tokens, and profiles. */ destroy(): void { this.stateGeneration++ this.pendingUMPUpdate = undefined this.statePersistencePending = false this.umpSyncStatus = 'unknown' this.underlying = undefined this.rootPrivilegedKeyManager = undefined this.authenticated = false this.rootPrimaryKey = undefined this.currentUMPToken = undefined this.pendingRegistrationToken = undefined this.presentationKey = undefined this.recoveryKey = undefined this.profiles = [] this.activeProfileId = DEFAULT_PROFILE_ID this.authenticationMode = 'presentation-key-and-password' this.authenticationFlow = 'unknown' } // --- Profile Management Methods --- /** * Lists all available profiles, including the default profile. * @returns Array of profile info objects, including an 'active' flag. */ listProfiles(): Array<{ id: number[] name: string createdAt: number | null active: boolean identityKey: string }> { if (!this.authenticated) { throw new Error('Not authenticated.') } const profileList = [ // Default profile { id: DEFAULT_PROFILE_ID, name: 'default', createdAt: null, // Default profile doesn't have a creation timestamp in the same way active: this.activeProfileId.every(x => x === 0), identityKey: new PrivateKey(this.rootPrimaryKey).toPublicKey().toString() }, // Other profiles ...this.profiles.map(p => ({ id: p.id, name: p.name, createdAt: p.createdAt, active: this.activeProfileId.every((x, i) => x === p.id[i]), identityKey: new PrivateKey(this.XOR(this.rootPrimaryKey as number[], p.primaryPad)).toPublicKey().toString() })) ] return profileList } /** * Adds a new profile with the given name. * Generates necessary pads and updates the UMP token. * Does not switch to the new profile automatically. * * @param name The desired name for the new profile. * @returns The ID of the newly created profile. */ async addProfile(name: string): Promise { return this.runStateTransition(async () => { if ( !this.authenticated || this.rootPrimaryKey == null || this.currentUMPToken == null || this.rootPrivilegedKeyManager == null ) { throw new Error('Wallet not fully initialized or authenticated.') } // Ensure name is unique (including 'default') const normalizedName = name.toLowerCase() if ( name === 'default' || this.pendingProfileNames.has(normalizedName) || this.profiles.some(p => p.name.toLowerCase() === normalizedName) ) { throw new Error(`Profile name "${name}" is already in use.`) } const newProfile: Profile = { name, id: Random(16), primaryPad: Random(32), privilegedPad: Random(32), createdAt: Math.floor(Date.now() / 1000) } // Reserve the case-insensitive name before the first await. The profile // itself remains unpublished until updateFactors accepts the new token. this.pendingProfileNames.add(normalizedName) try { // Only keep the new profile once the UMP token holds it, so a failed update // leaves the list as it was and a retry is not rejected as a duplicate. // Update the UMP token with the new profile list await this.updateFactors( this.currentUMPToken.passwordSalt, // Need to re-derive/decrypt factors needed for re-encryption await this.getFactor('passwordKey'), await this.getFactor('presentationKey'), await this.getFactor('recoveryKey'), this.rootPrimaryKey, await this.getFactor('privilegedKey'), // Get ROOT privileged key // Built last, after the awaits above: arguments are evaluated left to // right, and updateFactors captures the token it consumes before its first // await, so this list and that token are one consistent snapshot. Built // earlier, a profile added by an overlapping call would be dropped. [...this.profiles, newProfile] ) return newProfile.id } finally { this.pendingProfileNames.delete(normalizedName) } }) } /** * Deletes a profile by its ID. * Cannot delete the default profile. If the active profile is deleted, * it switches back to the default profile. * * @param profileId The 16-byte ID of the profile to delete. */ async deleteProfile(profileId: number[]): Promise { return this.runStateTransition(async () => { if ( !this.authenticated || this.rootPrimaryKey == null || this.currentUMPToken == null || this.rootPrivilegedKeyManager == null ) { throw new Error('Wallet not fully initialized or authenticated.') } if (profileId.every(x => x === 0)) { throw new Error('Cannot delete the default profile.') } const profileIndex = this.profiles.findIndex(p => p.id.every((x, i) => x === profileId[i])) if (profileIndex === -1) { throw new Error('Profile not found.') } // Remove the profile only once the UMP token no longer holds it, so a // failed update leaves the profile (and the active wallet) in place. const wasActive = this.activeProfileId.every((x, i) => x === profileId[i]) // If the deleted profile was active, switch to default if (wasActive) { await this.switchProfileForUpdate(DEFAULT_PROFILE_ID) // This rebuilds the wallet } // Update the UMP token try { await this.updateFactors( this.currentUMPToken.passwordSalt, await this.getFactor('passwordKey'), await this.getFactor('presentationKey'), await this.getFactor('recoveryKey'), this.rootPrimaryKey, await this.getFactor('privilegedKey'), // Get ROOT privileged key // Built last, after the awaits, for the same reason as in addProfile. this.profiles.filter(p => !p.id.every((x, i) => x === profileId[i])) ) } catch (error) { // Back to the profile we left, unless the token was published before the // failure. A failed switch back must not hide the original error. if (wasActive && this.profiles.some(p => p.id.every((x, i) => x === profileId[i]))) { await this.switchProfileForUpdate(profileId).catch(() => {}) } throw error } }) } /** * Switches the active profile. This re-derives keys and rebuilds the underlying wallet. * * @param profileId The 16-byte ID of the profile to switch to (use DEFAULT_PROFILE_ID for default). */ async switchProfile(profileId: number[]): Promise { return this.runStateTransition(async () => { if (!this.authenticated || this.rootPrimaryKey == null || this.rootPrivilegedKeyManager == null) throw new Error('Cannot switch profile: Wallet not authenticated or root keys missing.') if ( this.statePersistence != null && (profileId.length !== 16 || profileId.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) ) throw new Error('Invalid wallet profile ID.') await this.activateProfile(profileId) await this.persistState() }) } private switchProfileForUpdate(profileId: number[]): Promise { return this.statePersistence == null ? this.switchProfile(profileId) : this.activateProfile(profileId) } /** Build an internal profile wallet while an unpublished registration is not yet authenticated. */ private async activateProfile(profileId: number[]): Promise { this.assertTransitionCurrent() if (this.rootPrimaryKey == null || this.rootPrivilegedKeyManager == null) { throw new Error('Cannot activate profile: root keys are missing.') } let profilePrimaryKey: number[] let profilePrivilegedPad: number[] | undefined // Pad for the target profile if (profileId.every(x => x === 0)) { // Switching to default profile profilePrimaryKey = this.rootPrimaryKey profilePrivilegedPad = undefined // No pad for default } else { // Switching to a non-default profile const profile = this.profiles.find(p => p.id.every((x, i) => x === profileId[i])) if (profile == null) { throw new Error('Profile not found.') } profilePrimaryKey = this.XOR(this.rootPrimaryKey, profile.primaryPad) profilePrivilegedPad = profile.privilegedPad } // Create a *profile-specific* PrivilegedKeyManager. // It uses the ROOT manager internally but applies the profile's pad. const profilePrivilegedKeyManager = new PrivilegedKeyManager((reason: string) => mapAwaitFromSync( () => (this.rootPrivilegedKeyManager as any).getPrivilegedKey(reason), rootPrivileged => { const rootPrivilegedBytes = rootPrivileged.toArray() // Apply the profile's pad if applicable const profilePrivilegedBytes = profilePrivilegedPad == null ? rootPrivilegedBytes : this.XOR(rootPrivilegedBytes, profilePrivilegedPad) return new PrivateKey(profilePrivilegedBytes) } ) ) // Build the underlying wallet for the specific profile const generation = this.stateGeneration const candidate = await this.walletBuilder( profilePrimaryKey, profilePrivilegedKeyManager, // Pass the profile-specific manager profileId // Pass the ID of the profile being activated ) if (generation !== this.stateGeneration) throw new Error('Wallet session changed while activating the profile.') this.underlying = candidate this.activeProfileId = [...profileId] } // --- Key Management Methods --- /** * Changes the user's password. Re-wraps keys and updates the UMP token. */ async changePassword(newPassword: string): Promise { return this.runStateTransition(async () => { if ( !this.authenticated || this.currentUMPToken == null || this.rootPrimaryKey == null || this.rootPrivilegedKeyManager == null ) { throw new Error('Not authenticated or missing required data.') } const passwordSalt = Random(32) // Preserve current token's KDF metadata (or use manager's kdfConfig for legacy tokens) const kdfToUse = this.currentUMPToken.passwordKdf ?? this.kdfConfig const tempTokenForKdf = { passwordSalt, passwordKdf: kdfToUse } const newPasswordKey = await derivePasswordKey(tempTokenForKdf, toArray(newPassword, 'utf8')) // Decrypt existing factors needed for re-encryption, using the *root* privileged key manager const recoveryKey = await this.getFactor('recoveryKey') const presentationKey = await this.getFactor('presentationKey') const rootPrivilegedKey = await this.getFactor('privilegedKey') // Get ROOT privileged key await this.updateFactors( passwordSalt, newPasswordKey, presentationKey, recoveryKey, this.rootPrimaryKey, rootPrivilegedKey, // Pass the explicitly fetched root key this.profiles // Preserve existing profiles ) }) } /** * Retrieves the current recovery key. Requires privileged access. */ getRecoveryKey(): Promise { return promiseFromSync(() => { if (!this.authenticated || this.currentUMPToken == null || this.rootPrivilegedKeyManager == null) { throw new Error('Not authenticated or missing required data.') } return this.getFactor('recoveryKey') }) } /** * Changes the user's recovery key. Prompts user to save the new key. */ async changeRecoveryKey(): Promise { return this.runStateTransition(async () => { if ( !this.authenticated || this.currentUMPToken == null || this.rootPrimaryKey == null || this.rootPrivilegedKeyManager == null ) { throw new Error('Not authenticated or missing required data.') } // Decrypt existing factors needed const passwordKey = await this.getFactor('passwordKey') const presentationKey = await this.getFactor('presentationKey') const rootPrivilegedKey = await this.getFactor('privilegedKey') // Get ROOT privileged key // Generate and save new recovery key const newRecoveryKey = Random(32) await this.recoveryKeySaver(newRecoveryKey) await this.updateFactors( this.currentUMPToken.passwordSalt, passwordKey, presentationKey, newRecoveryKey, // Use the new key this.rootPrimaryKey, rootPrivilegedKey, this.profiles // Preserve profiles ) }) } /** * Changes the user's presentation key. */ async changePresentationKey(newPresentationKey: number[]): Promise { return this.runStateTransition(async () => { if ( !this.authenticated || this.currentUMPToken == null || this.rootPrimaryKey == null || this.rootPrivilegedKeyManager == null ) { throw new Error('Not authenticated or missing required data.') } if (newPresentationKey.length !== 32) { throw new Error('Presentation key must be 32 bytes.') } // A recovered WAB rotation may already have installed this presentation key. if ( this.statePersistence != null && toHex(sha256(newPresentationKey)) === toHex(this.currentUMPToken.presentationHash) ) return // Decrypt existing factors const recoveryKey = await this.getFactor('recoveryKey') const passwordKey = await this.getFactor('passwordKey') const rootPrivilegedKey = await this.getFactor('privilegedKey') // Get ROOT privileged key await this.updateFactors( this.currentUMPToken.passwordSalt, passwordKey, newPresentationKey, // Use the new key recoveryKey, this.rootPrimaryKey, rootPrivilegedKey, this.profiles // Preserve profiles ) // Update the temporarily stored key if it was set if (this.presentationKey != null) { this.presentationKey = newPresentationKey } }) } // --- Internal Helper Methods --- /** * Performs XOR operation on two byte arrays. */ private XOR(n1: number[], n2: number[]): number[] { if (n1.length !== n2.length) { // Provide more context in error throw new Error(`XOR length mismatch: ${n1.length} vs ${n2.length}`) } const r = Array.from({ length: n1.length }, () => 0) for (let i = 0; i < n1.length; i++) { r[i] = n1[i] ^ n2[i] } return r } /** * Helper to decrypt a specific factor (key) stored encrypted in the UMP token. * Requires the root privileged key manager. * @param factorName Name of the factor to decrypt ('passwordKey', 'presentationKey', 'recoveryKey', 'privilegedKey'). * @param getRoot If true and factorName is 'privilegedKey', returns the root privileged key bytes directly. * @returns The decrypted key bytes. */ protected async getFactor( factorName: 'passwordKey' | 'presentationKey' | 'recoveryKey' | 'privilegedKey' ): Promise { if (!this.authenticated || this.currentUMPToken == null || this.rootPrivilegedKeyManager == null) { throw new Error(`Cannot get factor "${factorName}": Wallet not ready.`) } const protocolID: [0 | 1 | 2, string] = [2, 'admin key wrapping'] // Protocol used for encrypting factors const keyID = '1' // Key ID used try { switch (factorName) { case 'passwordKey': return ( await this.rootPrivilegedKeyManager.decrypt({ ciphertext: this.currentUMPToken.passwordKeyEncrypted, protocolID, keyID }) ).plaintext case 'presentationKey': return ( await this.rootPrivilegedKeyManager.decrypt({ ciphertext: this.currentUMPToken.presentationKeyEncrypted, protocolID, keyID }) ).plaintext case 'recoveryKey': return ( await this.rootPrivilegedKeyManager.decrypt({ ciphertext: this.currentUMPToken.recoveryKeyEncrypted, protocolID, keyID }) ).plaintext case 'privilegedKey': { // This needs careful handling based on whether the ROOT or PROFILE key is needed. // This helper is mostly used for UMP updates, which need the ROOT key. // We retrieve the PrivateKey object first. const pk = await (this.rootPrivilegedKeyManager as any).getPrivilegedKey('UMP token update', true) // Force retrieval of root key return pk.toArray() // Return bytes } default: throw new Error(`Unknown factor name: ${factorName}`) } } catch (error) { this.telemetry.capture({ name: 'wallet-toolbox.authentication.factor-decryption.failed', component: CWI_COMPONENT, severity: 'error', attributes: { factor: factorName }, error }) const message = error instanceof Error ? error.message : 'Unknown error' throw new Error(`Failed to decrypt factor "${factorName}": ${message}`, { cause: error }) } } /** * Recomputes UMP token fields with updated factors and profiles, then publishes the update. * This operation requires the *root* privileged key and the *default* profile wallet. */ private async clearUnsubmittedUMPUpdate(): Promise { if (this.pendingUMPUpdate?.stage !== 'prepared') return await this.statePersistence?.savePendingUpdate(null) this.pendingUMPUpdate = undefined } private async updateFactors( passwordSalt: number[], passwordKey: number[], presentationKey: number[], recoveryKey: number[], rootPrimaryKey: number[], rootPrivilegedKey: number[], // Explicitly pass the root key bytes profiles?: Profile[] // Pass current/new profiles list ): Promise { if (!this.authenticated || this.rootPrimaryKey == null || this.currentUMPToken == null) { throw new Error('Wallet is not properly authenticated or missing data for update.') } // Ensure we have the OLD token to consume const oldTokenToConsume = { ...this.currentUMPToken } if (!oldTokenToConsume.currentOutpoint) { throw new Error('Cannot update UMP token: Old token has no outpoint.') } // Derive symmetrical encryption keys using XOR for the *root* keys const presentationPassword = new SymmetricKey(this.XOR(presentationKey, passwordKey)) const presentationRecovery = new SymmetricKey(this.XOR(presentationKey, recoveryKey)) const recoveryPassword = new SymmetricKey(this.XOR(recoveryKey, passwordKey)) const primaryPassword = new SymmetricKey(this.XOR(rootPrimaryKey, passwordKey)) // Use rootPrimaryKey // Build a temporary privileged key manager using the explicit ROOT privileged key const tempRootPrivilegedKeyManager = new PrivilegedKeyManager(() => promiseFromSync(() => new PrivateKey(rootPrivilegedKey)) ) // Encrypt profiles if provided let profilesEncrypted: number[] | undefined if (profiles != null && profiles.length > 0) { const profilesJson = JSON.stringify(profiles) const profilesBytes = toArray(profilesJson, 'utf8') profilesEncrypted = new SymmetricKey(rootPrimaryKey).encrypt(profilesBytes) as number[] } // Construct the new UMP token data. // IMPORTANT: For non-password updates (e.g. add/remove profile), preserve legacy // KDF layout exactly. Upgrading legacy tokens to v3 here would require re-deriving // passwordKey from plaintext password, which we do not have in this code path. const kdfMetadata = this.currentUMPToken.passwordKdf const newTokenData: UMPToken = { passwordSalt, passwordPresentationPrimary: presentationPassword.encrypt(rootPrimaryKey) as number[], passwordRecoveryPrimary: recoveryPassword.encrypt(rootPrimaryKey) as number[], presentationRecoveryPrimary: presentationRecovery.encrypt(rootPrimaryKey) as number[], passwordPrimaryPrivileged: primaryPassword.encrypt(rootPrivilegedKey) as number[], presentationRecoveryPrivileged: presentationRecovery.encrypt(rootPrivilegedKey) as number[], presentationHash: sha256(presentationKey), recoveryHash: sha256(recoveryKey), presentationKeyEncrypted: ( await tempRootPrivilegedKeyManager.encrypt({ plaintext: presentationKey, protocolID: [2, 'admin key wrapping'], keyID: '1' }) ).ciphertext, passwordKeyEncrypted: ( await tempRootPrivilegedKeyManager.encrypt({ plaintext: passwordKey, protocolID: [2, 'admin key wrapping'], keyID: '1' }) ).ciphertext, recoveryKeyEncrypted: ( await tempRootPrivilegedKeyManager.encrypt({ plaintext: recoveryKey, protocolID: [2, 'admin key wrapping'], keyID: '1' }) ).ciphertext, profilesEncrypted, // Add encrypted profiles ...(kdfMetadata == null ? {} : { umpVersion: 3, passwordKdf: kdfMetadata }) // currentOutpoint will be set after publishing } await this.prepareUMPUpdate(newTokenData, rootPrimaryKey) // We need the wallet built for the DEFAULT profile to publish the UMP token. // If the current active profile is not default, temporarily switch, publish, then switch back. const currentActiveId = this.activeProfileId let walletToUse: WalletInterface | undefined = this.underlying // Retain the original selection even if preparing the root wallet fails. try { if (!currentActiveId.every(x => x === 0)) { this.telemetry.capture({ name: 'wallet-toolbox.ump.profile-switch.started', component: CWI_COMPONENT, severity: 'debug', attributes: { reason: 'token-update' } }) await this.switchProfileForUpdate(DEFAULT_PROFILE_ID) // This rebuilds this.underlying walletToUse = this.underlying } if (walletToUse == null) { throw new Error('Default profile wallet could not be activated for UMP token update.') } // Publish the new token on-chain, consuming the old one newTokenData.currentOutpoint = await this.UMPTokenInteractor.buildAndSend( walletToUse, this.adminOriginator, newTokenData, oldTokenToConsume, // Consume the previous token this.umpActionCheckpoint() ) if (this.pendingUMPUpdate != null && this.pendingUMPUpdate.transaction == null) throw new Error('UMP interactor omitted the completed transaction checkpoint.') // A completed original transaction remains recoverable after teardown, // but it cannot restore the old account or replace a newer session. this.assertTransitionCurrent() // Update the manager's state this.currentUMPToken = newTokenData // Keep the profiles in step with the token that now holds them. Callers // pass a new list rather than changing this.profiles up front, so a // failed update leaves it untouched. if (profiles != null) { this.profiles = profiles } if (this.pendingUMPUpdate != null) { this.pendingUMPUpdate = { ...this.pendingUMPUpdate, stage: 'published', outpoint: newTokenData.currentOutpoint } await this.statePersistence?.savePendingUpdate(this.pendingUMPUpdate) } await this.persistState(currentActiveId) } catch (error) { await this.clearUnsubmittedUMPUpdate() throw error } finally { // Switch back if we temporarily switched if (!currentActiveId.every(x => x === 0)) { await this.switchProfileForUpdate(currentActiveId) this.telemetry.capture({ name: 'wallet-toolbox.ump.profile-switch.completed', component: CWI_COMPONENT, severity: 'debug', attributes: { reason: 'token-update' } }) } } if (this.pendingUMPUpdate != null) { await this.statePersistence?.savePendingUpdate(null) this.pendingUMPUpdate = undefined } } private async prepareUMPUpdate(token: UMPToken, rootPrimaryKey: number[]): Promise { this.assertTransitionCurrent() if (this.statePersistence != null) { if (this.UMPTokenInteractor.checkpointVersion !== 1) throw new Error('This UMP interactor cannot retain recoverable updates.') this.pendingUMPUpdate = { version: 1, operationId: toHex(Random(16)), rootIdentityKey: new PrivateKey(rootPrimaryKey).toPublicKey().toString(), previousSnapshot: this.saveSnapshot(), proposedToken: this.serializeUMPToken(token, true), activeProfileId: [...this.activeProfileId], stage: 'prepared' } try { await this.statePersistence.savePendingUpdate(this.pendingUMPUpdate) } catch (error) { this.pendingUMPUpdate = undefined throw error // No financial action has started. } } } private umpActionCheckpoint(): UMPActionCheckpoint | undefined { const pending = this.pendingUMPUpdate if (pending == null) return undefined const generation = this.stateGeneration return { operationId: pending.operationId, onStarting: async () => { this.assertTransitionCurrent() const submitting = { ...pending, stage: 'submitting' } as const await this.statePersistence?.savePendingUpdate(submitting) if (generation !== this.stateGeneration) { // The signing call has not run, so teardown can retire this admission. await this.statePersistence?.savePendingUpdate(null) this.assertTransitionCurrent() } this.pendingUMPUpdate = submitting }, onCompleted: async (transaction, outpoint) => { const signed = { ...pending, stage: 'signed', transaction, outpoint } as const if (generation === this.stateGeneration) this.pendingUMPUpdate = signed await this.statePersistence?.savePendingUpdate(signed) this.assertTransitionCurrent() } } } /** * Serializes a UMP token to binary format (Version 3 with KDF metadata, Version 2 with profiles). * V3 Layout: [1 byte version=3] + [11 * (varint len + bytes) for standard fields] + [1 byte profile_flag] + [IF flag=1 THEN varint len + profile bytes] + [1 byte kdf_flag] + [IF flag=1 THEN kdf metadata] + [varint len + outpoint bytes] */ private serializeUMPToken(token: UMPToken, allowUnpublished = false): number[] { if (!token.currentOutpoint && !allowUnpublished) { throw new Error('Token must have outpoint for serialization') } const writer = new Writer() const hasKdfMetadata = token.umpVersion === 3 && token.passwordKdf writer.writeUInt8(hasKdfMetadata ? 3 : 2) // Version 3 for KDF, 2 for legacy const writeArray = (arr: number[]) => { writer.writeVarIntNum(arr.length) writer.write(arr) } // Write standard fields in specific order writeArray(token.passwordSalt) // 0 writeArray(token.passwordPresentationPrimary) // 1 writeArray(token.passwordRecoveryPrimary) // 2 writeArray(token.presentationRecoveryPrimary) // 3 writeArray(token.passwordPrimaryPrivileged) // 4 writeArray(token.presentationRecoveryPrivileged) // 5 writeArray(token.presentationHash) // 6 writeArray(token.recoveryHash) // 7 writeArray(token.presentationKeyEncrypted) // 8 writeArray(token.passwordKeyEncrypted) // 9 writeArray(token.recoveryKeyEncrypted) // 10 // Write optional profiles field if (token.profilesEncrypted != null && token.profilesEncrypted.length > 0) { writer.writeUInt8(1) // Flag indicating profiles present writeArray(token.profilesEncrypted) } else { writer.writeUInt8(0) // Flag indicating no profiles } // V3: Write KDF metadata if (hasKdfMetadata) { writer.writeUInt8(1) // Flag indicating KDF metadata present writer.writeUInt8(token.umpVersion!) // On-chain UMP version const algorithmBytes = toArray(token.passwordKdf!.algorithm, 'utf8') writeArray(algorithmBytes) // Serialize KDF params as JSON const kdfParams: Record = { iterations: token.passwordKdf!.iterations } if (token.passwordKdf!.memoryKiB !== undefined) { kdfParams.memoryKiB = token.passwordKdf!.memoryKiB } if (token.passwordKdf!.parallelism !== undefined) { kdfParams.parallelism = token.passwordKdf!.parallelism } if (token.passwordKdf!.hashLength !== undefined) { kdfParams.hashLength = token.passwordKdf!.hashLength } const kdfParamsBytes = toArray(JSON.stringify(kdfParams), 'utf8') writeArray(kdfParamsBytes) } else if (writer.toArray()[0] === 3) { // Version 3 without KDF metadata (shouldn't happen, but handle gracefully) writer.writeUInt8(0) // Flag indicating no KDF metadata } // Write outpoint string const outpointBytes = toArray(token.currentOutpoint ?? '', 'utf8') writer.writeVarIntNum(outpointBytes.length) writer.write(outpointBytes) return writer.toArray() } /** * Deserializes a UMP token from binary format (Handles Version 1, 2, and 3). */ private deserializeUMPToken(bin: number[], allowUnpublished = false): UMPToken { const reader = new Reader(bin) const version = reader.readUInt8() if (version !== 1 && version !== 2 && version !== 3) { throw new Error(`Unsupported UMP token serialization version: ${version}`) } const readArray = (): number[] => { const length = reader.readVarIntNumStrict(false) if (length <= 0 || length > MAX_STATE_SNAPSHOT_BYTES) { throw new Error('UMP token field exceeds allowed bounds.') } return reader.read(length) } // Read standard fields (order matches serialization) const passwordSalt = readArray() // 0 const passwordPresentationPrimary = readArray() // 1 const passwordRecoveryPrimary = readArray() // 2 const presentationRecoveryPrimary = readArray() // 3 const passwordPrimaryPrivileged = readArray() // 4 const presentationRecoveryPrivileged = readArray() // 5 const presentationHash = readArray() // 6 const recoveryHash = readArray() // 7 const presentationKeyEncrypted = readArray() // 8 const passwordKeyEncrypted = readArray() // 9 const recoveryKeyEncrypted = readArray() // 10 // Read optional profiles (V2 and V3) let profilesEncrypted: number[] | undefined if (version >= 2) { const profilesFlag = reader.readUInt8() if (profilesFlag === 1) { profilesEncrypted = readArray() } } // Read KDF metadata (V3 only) let umpVersion: number | undefined let passwordKdf: UMPToken['passwordKdf'] if (version === 3) { const kdfFlag = reader.readUInt8() if (kdfFlag === 1) { umpVersion = reader.readUInt8() // On-chain UMP version const algorithmBytes = readArray() const algorithm = toUTF8(algorithmBytes) as 'pbkdf2-sha512' | 'argon2id' const kdfParamsBytes = readArray() const kdfParamsJson = toUTF8(kdfParamsBytes) const kdfParams = JSON.parse(kdfParamsJson) as Record passwordKdf = { algorithm, iterations: kdfParams.iterations as number, memoryKiB: kdfParams.memoryKiB as number | undefined, parallelism: kdfParams.parallelism as number | undefined, hashLength: kdfParams.hashLength as number | undefined } if (!isValidKdfConfig(passwordKdf)) { throw new Error('Serialized UMP token contains unsupported or unsafe KDF parameters.') } } } // Read outpoint string const currentOutpoint = readSerializedOutpoint(reader, allowUnpublished) const token: UMPToken = { passwordSalt, passwordPresentationPrimary, passwordRecoveryPrimary, presentationRecoveryPrimary, passwordPrimaryPrivileged, presentationRecoveryPrivileged, presentationHash, recoveryHash, presentationKeyEncrypted, passwordKeyEncrypted, recoveryKeyEncrypted, profilesEncrypted, ...(currentOutpoint.length > 0 ? { currentOutpoint } : {}), umpVersion, passwordKdf } return token } /** * Sets up the root key infrastructure after authentication or loading from snapshot. * Initializes the root primary key, root privileged key manager, loads profiles, * and sets the authenticated flag. Does NOT switch profile initially. * * @param rootPrimaryKey The user's root primary key (32 bytes). * @param ephemeralRootPrivilegedKey Optional root privileged key (e.g., during recovery flows). */ private setupRoot(rootKey: number[], ephemeralRootPrivilegedKey?: number[], authenticated = true): Promise { if (this.currentUMPToken == null) { throw new Error('A UMP token must exist before setting up root infrastructure!') } this.rootPrimaryKey = rootKey // Store ephemeral key if provided, for one-time use by the manager let oneTimePrivilegedKey: PrivateKey | undefined = ephemeralRootPrivilegedKey == null ? undefined : new PrivateKey(ephemeralRootPrivilegedKey) // Create the ROOT PrivilegedKeyManager this.rootPrivilegedKeyManager = new PrivilegedKeyManager(async (reason: string) => { // 1. Use one-time key if available (for recovery) if (oneTimePrivilegedKey != null) { const tempKey = oneTimePrivilegedKey oneTimePrivilegedKey = undefined // Consume it return tempKey } // 2. Otherwise, derive from password const password = await this.passwordRetriever(reason, async (passwordCandidate: string) => { try { const derivedPasswordKey = await derivePasswordKey(this.currentUMPToken!, toArray(passwordCandidate, 'utf8')) const privilegedDecryptor = this.XOR(this.rootPrimaryKey!, derivedPasswordKey) const decryptedPrivileged = new SymmetricKey(privilegedDecryptor).decrypt( this.currentUMPToken!.passwordPrimaryPrivileged ) as number[] return !!decryptedPrivileged // Test passes if decryption works } catch { // Decryption failure means the password candidate is wrong — this is the // expected rejection path for an incorrect password. Returning false causes // the password-retriever loop to prompt the user again rather than crashing. return false } }) // Decrypt the root privileged key using the confirmed password (with token-driven KDF) const derivedPasswordKey = await derivePasswordKey(this.currentUMPToken!, toArray(password, 'utf8')) const privilegedDecryptor = this.XOR(this.rootPrimaryKey!, derivedPasswordKey) const rootPrivilegedBytes = new SymmetricKey(privilegedDecryptor).decrypt( this.currentUMPToken!.passwordPrimaryPrivileged ) as number[] return new PrivateKey(rootPrivilegedBytes) // Return the ROOT key object }) // Decrypt and load profiles if present in the token this.profiles = [] // Clear existing profiles before loading if (this.currentUMPToken.profilesEncrypted != null && this.currentUMPToken.profilesEncrypted.length > 0) { try { const decryptedProfileBytes = new SymmetricKey(rootKey).decrypt( this.currentUMPToken.profilesEncrypted ) as number[] const profilesJson = toUTF8(decryptedProfileBytes) const profiles = JSON.parse(profilesJson) as unknown if (!Array.isArray(profiles) || profiles.length > 1000 || !profiles.every(isValidProfile)) { throw new Error('Decrypted profile data is invalid or exceeds supported bounds.') } this.profiles = profiles } catch (error) { this.profiles = [] this.telemetry.capture({ name: 'wallet-toolbox.profile.load-failed', component: CWI_COMPONENT, severity: 'error', error }) const message = error instanceof Error ? error.message : 'Unknown error' throw new Error(`Failed to load profiles: ${message}`, { cause: error }) } } this.authenticated = authenticated // Note: We don't call switchProfile here anymore. // It's called by the auth methods (providePassword/provideRecoveryKey) or loadSnapshot after this. return Promise.resolve() } /* * --------------------------------------------------------------------------------------- * Standard WalletInterface methods proxying to the *active* underlying wallet. * Includes authentication checks and admin originator protection. * --------------------------------------------------------------------------------------- */ private assertReady(originator?: string): void { if ( this.statePersistence != null && (this.stateTransitionActive || this.statePersistencePending || this.pendingUMPUpdate != null) ) throw new Error('Wallet state is changing or needs recovery. Retry after its state is saved.') if (!this.authenticated) { throw new Error('User is not authenticated.') } if (this.underlying == null) { // This might happen if authentication succeeded but profile switching failed throw new Error('Underlying wallet for the active profile is not initialized.') } if (originator === this.adminOriginator) { throw new Error('External applications are not allowed to use the admin originator.') } } // Example proxy method (repeat pattern for all others) getPublicKey( args: GetPublicKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.getPublicKey(args, originator) }) } revealCounterpartyKeyLinkage( args: RevealCounterpartyKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.revealCounterpartyKeyLinkage(args, originator) }) } revealSpecificKeyLinkage( args: RevealSpecificKeyLinkageArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.revealSpecificKeyLinkage(args, originator) }) } encrypt(args: WalletEncryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.encrypt(args, originator) }) } decrypt(args: WalletDecryptArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.decrypt(args, originator) }) } createHmac(args: CreateHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.createHmac(args, originator) }) } verifyHmac(args: VerifyHmacArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.verifyHmac(args, originator) }) } createSignature( args: CreateSignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.createSignature(args, originator) }) } verifySignature( args: VerifySignatureArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.verifySignature(args, originator) }) } createAction( args: CreateActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.createAction(args, originator) }) } signAction(args: SignActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.signAction(args, originator) }) } abortAction(args: AbortActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.abortAction(args, originator) }) } listActions(args: ListActionsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.listActions(args, originator) }) } internalizeAction( args: InternalizeActionArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.internalizeAction(args, originator) }) } listOutputs(args: ListOutputsArgs, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.listOutputs(args, originator) }) } relinquishOutput( args: RelinquishOutputArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.relinquishOutput(args, originator) }) } acquireCertificate( args: AcquireCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.acquireCertificate(args, originator) }) } listCertificates( args: ListCertificatesArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.listCertificates(args, originator) }) } proveCertificate( args: ProveCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.proveCertificate(args, originator) }) } relinquishCertificate( args: RelinquishCertificateArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.relinquishCertificate(args, originator) }) } discoverByIdentityKey( args: DiscoverByIdentityKeyArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.discoverByIdentityKey(args, originator) }) } discoverByAttributes( args: DiscoverByAttributesArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.discoverByAttributes(args, originator) }) } isAuthenticated(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { if (!this.authenticated) { throw new Error('User is not authenticated.') } if (originator === this.adminOriginator) { throw new Error('External applications are not allowed to use the admin originator.') } return { authenticated: true } }) } async waitForAuthentication( _: {}, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { if (originator === this.adminOriginator) { throw new Error('External applications are not allowed to use the admin originator.') } while (!this.authenticated || this.underlying == null) { await new Promise(resolve => setTimeout(resolve, 100)) } return this.underlying.waitForAuthentication({}, originator) } getHeight(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.getHeight({}, originator) }) } getHeaderForHeight( args: GetHeaderArgs, originator?: OriginatorDomainNameStringUnder250Bytes ): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.getHeaderForHeight(args, originator) }) } getNetwork(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.getNetwork({}, originator) }) } getVersion(_: {}, originator?: OriginatorDomainNameStringUnder250Bytes): Promise { return promiseFromSync(() => { this.assertReady(originator) return this.underlying!.getVersion({}, originator) }) } }