// Copyright 2017-2026 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 import type { DilithiumType } from '../dilithium.js'; import type { Keypair } from '../types.js'; import { argon2id } from '@noble/hashes/argon2'; import { u8aEq } from '@polkadot/util'; import { encodeAddress } from '../address/encode.js'; import { base64Encode } from '../base64/index.js'; import { dilithiumAccountFromPublic } from './account.js'; import { dilithiumSizes } from './scheme.js'; /** The wallet file `quantus-cli` writes to ~/.quantus/wallets/.json */ export interface QuantusCliWallet { address: string; aes_nonce: number[]; argon2_params: string; argon2_salt: number[]; created_at?: string; encrypted_data: number[]; encryption_version: number; kyber_ciphertext?: number[]; kyber_public_key?: number[]; name?: string; wallet_type?: string; } export interface QuantusCliImport { /** The 32-byte account id the file claims, verified against the key. */ accountId: Uint8Array; /** The derivation path the CLI recorded, for display. `m/` for a raw-seed wallet. */ derivationPath: string | null; keypair: Keypair; /** Whether the file carried a mnemonic. It is never returned — see below. */ hadMnemonic: boolean; name: string | null; type: DilithiumType; } /** The only container version this understands. */ const SUPPORTED_VERSION = 2; const SCHEME_TO_TYPE: Record = { 'ml-dsa-65': 'dilithium65', 'ml-dsa-87': 'dilithium87' }; const TYPE_TO_SCHEME: Record = { dilithium65: 'ml-dsa-65', dilithium87: 'ml-dsa-87' }; /** * Argon2 parameters written on export. * * Deliberately the same values `quantus-cli` 2.2.2 uses rather than something * stronger. The parameters travel in the file and the CLI reads them, so in * principle anything works — but "in principle" is doing load-bearing work * there, and a wallet that a slightly older CLI cannot open is a worse outcome * than one whose KDF is tuned conservatively. Raise them when there is a reason * to believe every CLI in circulation honours the PHC string. */ const EXPORT_ARGON2: Argon2Params = { m: 19456, p: 1, t: 2 }; /** * SS58 prefix for the `address` field of an exported wallet. * * Fixed rather than a parameter: this is the Quantus CLI's format, the CLI only * ever deals with Quantus, and an address at any other prefix would be one it * could not match to the key inside. */ const QUANTUS_PREFIX = 189; /** What the CLI records for a wallet with no derivation — a raw seed. */ const NO_DERIVATION = 'm/'; interface Argon2Params { m: number; p: number; t: number; } /** * Parse the PHC string the CLI stores, e.g. * `$argon2id$v=19$m=19456,t=2,p=1$`. * * Read rather than hardcoded. The parameters are in the file because they are * expected to change, and a build that assumed today's values would fail to open * an older or newer wallet with a *wrong password* error — which is the least * useful thing it could say, since the password would be right. */ function parseArgon2Params (phc: string): Argon2Params { const match = /^\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)/.exec(phc); if (!match) { throw new Error(`Unsupported Argon2 parameters in wallet: ${phc}`); } return { m: parseInt(match[1], 10), p: parseInt(match[3], 10), t: parseInt(match[2], 10) }; } function assertSupported (wallet: QuantusCliWallet): void { if (wallet.encryption_version !== SUPPORTED_VERSION) { throw new Error(`Unsupported quantus-cli wallet encryption version ${wallet.encryption_version}; this build understands version ${SUPPORTED_VERSION}`); } // An ML-KEM envelope mode, either planned or optional — the fields exist and // are empty in every wallet seen so far. Refuse rather than ignore them and // decrypt by the path we do know: a wallet encrypted to an ML-KEM key is not // one we can open, and treating it as if it were would fail later and more // confusingly, most likely as a bad-password error. if (wallet.kyber_ciphertext?.length || wallet.kyber_public_key?.length) { throw new Error('This wallet uses ML-KEM envelope encryption, which is not supported'); } } /** * Decrypt and validate a `quantus-cli` wallet file. * * The result is exactly what importing the same account by mnemonic would * produce: a keypair, and nothing that can regenerate the rest of the tree. The * CLI stores a mnemonic inside every HD wallet and this **deliberately does not * return it** — the extension's posture is that a storage password unlocks * signing and nothing on disk regenerates the wallet. `hadMnemonic` says one was * present, so a caller can tell the user where their backup lives, without the * phrase itself passing through. * * Async because AES-GCM is WebCrypto, which has no synchronous form. That is * also why this is an edge conversion rather than something `createFromJson` * learns: that path is synchronous and should stay so, and the keyring should * keep exactly one on-disk format. */ export async function dilithiumFromCliWallet (wallet: QuantusCliWallet, password = ''): Promise { assertSupported(wallet); const { m, p, t } = parseArgon2Params(wallet.argon2_params); const key = argon2id( new TextEncoder().encode(password), new Uint8Array(wallet.argon2_salt), { dkLen: 32, m, p, t } ); let plaintext: Uint8Array; try { const aesKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']); plaintext = new Uint8Array( await crypto.subtle.decrypt( { iv: new Uint8Array(wallet.aes_nonce), name: 'AES-GCM' }, aesKey, new Uint8Array(wallet.encrypted_data) ) ); } catch { // AES-GCM authenticates, so this is a wrong password or a corrupted file and // there is no way to tell which from here. throw new Error('Unable to decrypt the wallet; the password may be incorrect'); } const decoded = JSON.parse(new TextDecoder().decode(plaintext)) as { keypair?: { private_key?: number[]; public_key?: number[]; scheme?: string }; derivation_path?: string; mnemonic?: string | null; name?: string; }; const scheme = decoded.keypair?.scheme; const type = scheme ? SCHEME_TO_TYPE[scheme] : undefined; if (!type) { throw new Error(`Unsupported signature scheme in wallet: ${scheme ?? 'none'}`); } if (!decoded.keypair?.public_key || !decoded.keypair.private_key) { throw new Error('Wallet contains no keypair'); } const publicKey = new Uint8Array(decoded.keypair.public_key); const secretKey = new Uint8Array(decoded.keypair.private_key); const sizes = dilithiumSizes(type); if (publicKey.length !== sizes.publicKey || secretKey.length !== sizes.secretKey) { throw new Error(`Wallet key lengths do not match ${scheme}: expected ${sizes.publicKey}/${sizes.secretKey}, found ${publicKey.length}/${secretKey.length}`); } // The address travels outside the encrypted blob, so it is the one field an // attacker can edit without knowing the password. Left unchecked, a tampered // file would import cleanly and produce an account displaying an address it // cannot sign for — the same failure the account-JSON check in the keyring // exists to prevent. const accountId = dilithiumAccountFromPublic(publicKey); return { accountId, derivationPath: decoded.derivation_path ?? null, hadMnemonic: !!decoded.mnemonic, keypair: { publicKey, secretKey }, name: decoded.name ?? wallet.name ?? null, type }; } /** * Whether a decrypted wallet's key matches the address its file claims. * * Separate from the decrypt so the caller can render the mismatch rather than * only catch it — "this file's address does not match its key" is a different * message from "wrong password", and a user can act on the difference. */ export function cliWalletAddressMatches (accountId: Uint8Array, decodedAddress: Uint8Array): boolean { return u8aEq(accountId, decodedAddress); } export interface QuantusCliExportInput { /** The derivation path, where known. Omit for a raw-seed account. */ derivationPath?: string | null; keypair: Keypair; name: string; type: DilithiumType; } /** * Write a `quantus-cli` wallet file. * * The mnemonic is **always null**. That is not a limitation worked around: the * CLI's format has a null-mnemonic shape and writes one itself for every * raw-seed wallet, and a wallet in that shape lists, opens and spends normally. * What it cannot do is `export --format mnemonic` or derive further accounts — * the honest consequence of the extension never storing a phrase it showed once. * * Without this, importing a CLI wallet (see `dilithiumFromCliWallet`) is a * one-way door, and an extension backup is readable only by polkadot-js-format * tooling. */ export async function dilithiumToCliWallet ({ derivationPath, keypair, name, type }: QuantusCliExportInput, password = ''): Promise { const sizes = dilithiumSizes(type); if (keypair.publicKey.length !== sizes.publicKey || keypair.secretKey.length !== sizes.secretKey) { throw new Error(`Key lengths do not match ${type}: expected ${sizes.publicKey}/${sizes.secretKey}, found ${keypair.publicKey.length}/${keypair.secretKey.length}`); } const payload = JSON.stringify({ derivation_path: derivationPath || NO_DERIVATION, keypair: { private_key: Array.from(keypair.secretKey), public_key: Array.from(keypair.publicKey), scheme: TYPE_TO_SCHEME[type] }, metadata: { algorithm: TYPE_TO_SCHEME[type].toUpperCase(), // So a CLI maintainer reading a bug report can tell where the file came // from without having to guess from its shape. exported_by: 'quantus-extension', version: '1.0.0' }, mnemonic: null, name }); const salt = crypto.getRandomValues(new Uint8Array(16)); const nonce = crypto.getRandomValues(new Uint8Array(12)); const key = argon2id( new TextEncoder().encode(password), salt, { dkLen: 32, m: EXPORT_ARGON2.m, p: EXPORT_ARGON2.p, t: EXPORT_ARGON2.t } ); const aesKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']); const encrypted = new Uint8Array( await crypto.subtle.encrypt( { iv: nonce, name: 'AES-GCM' }, aesKey, new TextEncoder().encode(payload) ) ); return { address: encodeAddress(dilithiumAccountFromPublic(keypair.publicKey), QUANTUS_PREFIX), aes_nonce: Array.from(nonce), // The salt goes into the PHC string as well as its own field, because that // is what the CLI writes and a reader may take it from either. argon2_params: `$argon2id$v=19$m=${EXPORT_ARGON2.m},t=${EXPORT_ARGON2.t},p=${EXPORT_ARGON2.p}$${base64Unpadded(salt)}`, argon2_salt: Array.from(salt), created_at: new Date().toISOString(), encrypted_data: Array.from(encrypted), encryption_version: SUPPORTED_VERSION, kyber_ciphertext: [], kyber_public_key: [], name, wallet_type: 'hot' }; } /** Unpadded standard base64, as the PHC string format requires. */ function base64Unpadded (data: Uint8Array): string { return base64Encode(data).replace(/=+$/, ''); }