The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(wallet): move mnemonic derivation into the wallet module
Steven Enamakel591a0da3a182
diff --git a/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts b/app/src/features/wallet/setupLocalWalletFromMnemonic.test.tsindex 30eb80642a..692c7dd975 100644--- a/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts+++ b/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts@@ -4,8 +4,37 @@ import { persistLocalWalletFromMnemonic } from './setupLocalWalletFromMnemonic';const mockSetupLocalWallet = vi.fn();const mockEncryptSecret = vi.fn();+const mockDeriveRecoveryMaterial = vi.fn();++const canonicalSeed = Uint8Array.from(+ '5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4'.match(/.{2}/g) ?? [],+ byte => Number.parseInt(byte, 16)+);+const canonicalAccounts = [+ {+ chain: 'evm' as const,+ address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',+ derivationPath: "m/44'/60'/0'/0/0",+ },+ {+ chain: 'btc' as const,+ address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',+ derivationPath: "m/44'/0'/0'/0/0",+ },+ {+ chain: 'solana' as const,+ address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',+ derivationPath: "m/44'/501'/0'/0'",+ },+ {+ chain: 'tron' as const,+ address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',+ derivationPath: "m/44'/195'/0'/0/0",+ },+];vi.mock('../../services/walletApi', () => ({+ deriveRecoveryMaterial: (...args: unknown[]) => mockDeriveRecoveryMaterial(...args),setupLocalWallet: (...args: unknown[]) => mockSetupLocalWallet(...args),}));@@ -14,8 +43,12 @@ vi.mock('../../utils/tauriCommands/auth', () => ({}));describe('persistLocalWalletFromMnemonic', () => {- it('derives multi-chain wallet metadata and persists it after storing the AES key', async () => {+ it('uses module-derived seed and accounts before persisting the wallet', async () => {const setEncryptionKey = vi.fn(async () => undefined);+ mockDeriveRecoveryMaterial.mockResolvedValueOnce({+ seed: new Uint8Array(canonicalSeed),+ accounts: canonicalAccounts,+ });mockSetupLocalWallet.mockResolvedValueOnce({configured: true,onboardingCompleted: true,@@ -33,6 +66,10 @@ describe('persistLocalWalletFromMnemonic', () => {await persistLocalWalletFromMnemonic({ mnemonic, source: 'generated', setEncryptionKey });+ expect(mockDeriveRecoveryMaterial).toHaveBeenCalledWith(+ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'+ );+expect(setEncryptionKey).toHaveBeenCalledWith('dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1');@@ -41,28 +78,7 @@ describe('persistLocalWalletFromMnemonic', () => {source: 'generated',mnemonicWordCount: 12,encryptedMnemonic: 'enc2:wallet-secret',- accounts: [- {- chain: 'evm',- address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',- derivationPath: "m/44'/60'/0'/0/0",- },- {- chain: 'btc',- address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',- derivationPath: "m/44'/0'/0'/0/0",- },- {- chain: 'solana',- address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',- derivationPath: "m/44'/501'/0'/0'",- },- {- chain: 'tron',- address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',- derivationPath: "m/44'/195'/0'/0/0",- },- ],+ accounts: canonicalAccounts,});});@@ -77,12 +93,18 @@ describe('persistLocalWalletFromMnemonic', () => {expect(setEncryptionKey).not.toHaveBeenCalled();expect(mockEncryptSecret).not.toHaveBeenCalled();expect(mockSetupLocalWallet).not.toHaveBeenCalled();+ expect(mockDeriveRecoveryMaterial).not.toHaveBeenCalled();});it('rejects empty encrypted mnemonic output before persisting wallet state', async () => {const setEncryptionKey = vi.fn(async () => undefined);mockSetupLocalWallet.mockReset();mockEncryptSecret.mockReset();+ mockDeriveRecoveryMaterial.mockReset();+ mockDeriveRecoveryMaterial.mockResolvedValueOnce({+ seed: new Uint8Array(canonicalSeed),+ accounts: canonicalAccounts,+ });mockEncryptSecret.mockResolvedValueOnce({ result: ' ' });await expect(diff --git a/app/src/features/wallet/setupLocalWalletFromMnemonic.ts b/app/src/features/wallet/setupLocalWalletFromMnemonic.tsindex 9d36a8c628..9609030b53 100644--- a/app/src/features/wallet/setupLocalWalletFromMnemonic.ts+++ b/app/src/features/wallet/setupLocalWalletFromMnemonic.ts@@ -1,9 +1,9 @@-import { setupLocalWallet } from '../../services/walletApi';import {- deriveAesKeyFromMnemonic,- deriveWalletAccountsFromMnemonic,+ deriveRecoveryMaterial,+ setupLocalWallet,type WalletSetupSource,-} from '../../utils/cryptoKeys';+} from '../../services/walletApi';+import { deriveAesKeyFromSeed } from '../../utils/cryptoKeys';import { openhumanEncryptSecret } from '../../utils/tauriCommands/auth';export async function persistLocalWalletFromMnemonic(args: {@@ -22,7 +22,8 @@ export async function persistLocalWalletFromMnemonic(args: {throw new Error('Recovery phrase is required.');}const normalizedMnemonic = words.join(' ');- const aesKey = deriveAesKeyFromMnemonic(normalizedMnemonic);+ const recoveryMaterial = await deriveRecoveryMaterial(normalizedMnemonic);+ const aesKey = deriveAesKeyFromSeed(recoveryMaterial.seed);const encryptedMnemonic = (await openhumanEncryptSecret(normalizedMnemonic)).result?.trim();if (!encryptedMnemonic) {throw new Error('Failed to secure recovery phrase. Please try again.');@@ -34,7 +35,7 @@ export async function persistLocalWalletFromMnemonic(args: {source,mnemonicWordCount: words.length,encryptedMnemonic,- accounts: deriveWalletAccountsFromMnemonic(normalizedMnemonic),+ accounts: recoveryMaterial.accounts,force,});}diff --git a/app/src/services/walletApi.test.ts b/app/src/services/walletApi.test.tsindex 6ecad3cab0..171aa16ef0 100644--- a/app/src/services/walletApi.test.ts+++ b/app/src/services/walletApi.test.ts@@ -58,6 +58,23 @@ describe('walletApi', () => {expect(result).toBe(false);});+ it('deriveRecoveryMaterial requests module-owned seed and account derivation', async () => {+ const seed = Array.from({ length: 64 }, (_, index) => index);+ const accounts = [{ chain: 'evm' as const, address: '0xabc', derivationPath: "m/44'/60'/0'/0/0" }];+ mockCallCoreRpc.mockResolvedValueOnce({ result: { seed, accounts } });++ const { deriveRecoveryMaterial } = await import('./walletApi');+ const result = await deriveRecoveryMaterial('secret phrase');++ expect(mockCallCoreRpc).toHaveBeenCalledWith({+ method: 'openhuman.wallet_derive_recovery_material',+ params: { phrase: 'secret phrase' },+ });+ expect(result.seed).toEqual(Uint8Array.from({ length: 64 }, (_, index) => index));+ expect(seed).toEqual(new Array(64).fill(0));+ expect(result.accounts).toEqual(accounts);+ });+it('setupLocalWallet calls the wallet setup RPC with params', async () => {const payload = {consentGranted: true,diff --git a/app/src/services/walletApi.ts b/app/src/services/walletApi.tsindex 07d2c33190..96daec0ed3 100644--- a/app/src/services/walletApi.ts+++ b/app/src/services/walletApi.ts@@ -29,6 +29,12 @@ export interface WalletAccount {derivationPath: string;}+export interface WalletRecoveryMaterial {+ /** Standard BIP-39 seed; consumed and cleared by the storage-key KDF. */+ seed: Uint8Array;+ accounts: WalletAccount[];+}+export interface GeneratedRecoveryPhrase {phrase: string;wordCount: number;@@ -85,6 +91,19 @@ export const validateRecoveryPhrase = async (phrase: string): Promise<boolean> =return response.result.valid;};+/** Derive the generic storage-key seed and public accounts through TinyWallet. */+export const deriveRecoveryMaterial = async (phrase: string): Promise<WalletRecoveryMaterial> => {+ const response = await callCoreRpc<{+ result: { seed: number[]; accounts: WalletAccount[] };+ }>({+ method: 'openhuman.wallet_derive_recovery_material',+ params: { phrase },+ });+ const seed = Uint8Array.from(response.result.seed);+ response.result.seed.fill(0);+ return { seed, accounts: response.result.accounts };+};+export const setupLocalWallet = async (params: SetupWalletParams): Promise<WalletStatus> => {const response = await callCoreRpc<{ result: WalletStatus }>({method: 'openhuman.wallet_setup',diff --git a/app/src/utils/cryptoKeys.test.ts b/app/src/utils/cryptoKeys.test.tsindex 70b936ebee..40b9429969 100644--- a/app/src/utils/cryptoKeys.test.ts+++ b/app/src/utils/cryptoKeys.test.ts@@ -1,193 +1,29 @@import { describe, expect, it } from 'vitest';-import { mnemonicToSeedSync } from '@scure/bip39';-import {- deriveAesKeyFromMnemonic,- deriveAesKeyFromSeed,- deriveBtcAddressFromMnemonic,- deriveEvmAddressFromMnemonic,- deriveSolanaAddressFromMnemonic,- deriveTronAddressFromMnemonic,- deriveWalletAccountsFromMnemonic,- generateMnemonicPhrase,- MNEMONIC_GENERATE_WORD_COUNT,- validateMnemonicPhrase,-} from './cryptoKeys';+import { deriveAesKeyFromSeed } from './cryptoKeys';-// Known-good 12-word BIP39 mnemonic for deterministic assertions.-const KNOWN_MNEMONIC =- 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';+// BIP-39's published empty-passphrase seed for `abandon` x11 + `about`.+const CANONICAL_SEED_HEX =+ '5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4';-describe('MNEMONIC_GENERATE_WORD_COUNT', () => {- it('is 12', () => {- expect(MNEMONIC_GENERATE_WORD_COUNT).toBe(12);- });-});--describe('generateMnemonicPhrase', () => {- it('returns a 12-word phrase', () => {- const phrase = generateMnemonicPhrase();- expect(phrase.trim().split(/\s+/)).toHaveLength(12);- });-- it('returns a valid BIP39 mnemonic', () => {- const phrase = generateMnemonicPhrase();- expect(validateMnemonicPhrase(phrase)).toBe(true);- });-- it('produces a different phrase each call', () => {- const a = generateMnemonicPhrase();- const b = generateMnemonicPhrase();- // Astronomically unlikely to collide; guards against a no-op implementation.- expect(a).not.toBe(b);- });-});--describe('validateMnemonicPhrase', () => {- it('returns true for the known valid mnemonic', () => {- expect(validateMnemonicPhrase(KNOWN_MNEMONIC)).toBe(true);- });-- it('returns false for an empty string', () => {- expect(validateMnemonicPhrase('')).toBe(false);- });-- it('returns false for a single random word', () => {- expect(validateMnemonicPhrase('abandon')).toBe(false);- });-- it('returns false for 12 non-BIP39 words', () => {- expect(- validateMnemonicPhrase('foo bar baz qux quux corge grault garply waldo fred plugh xyzzy')- ).toBe(false);- });-- it('returns false for an otherwise valid phrase with one word replaced by a non-wordlist word', () => {- const tampered = KNOWN_MNEMONIC.replace('abandon', 'xxxxxxxx');- expect(validateMnemonicPhrase(tampered)).toBe(false);- });-});--describe('deriveAesKeyFromMnemonic', () => {- it('returns a 64-character hex string (256-bit key)', () => {- const key = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);- expect(key).toMatch(/^[0-9a-f]{64}$/);- });-- it('is deterministic for the same mnemonic', () => {- const key1 = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);- const key2 = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);- expect(key1).toBe(key2);- });-- it('produces a different key for a different mnemonic', () => {- const other = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong';- expect(validateMnemonicPhrase(other)).toBe(true);- const keyA = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);- const keyB = deriveAesKeyFromMnemonic(other);- expect(keyA).not.toBe(keyB);- });-- it('returns a fixed known value for the all-abandon mnemonic', () => {- // Pinned output for salt='openhuman-aes-key-v1', PBKDF2-SHA256, c=100000, dkLen=32.- // If this assertion fails, the KDF parameters or salt have changed — update intentionally.- const key = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);- expect(key).toBe('dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1');- });-});+function bytesFromHex(hex: string): Uint8Array {+ return Uint8Array.from(hex.match(/.{2}/g) ?? [], byte => Number.parseInt(byte, 16));+}describe('deriveAesKeyFromSeed', () => {- it('preserves the existing storage key for the canonical BIP-39 seed', () => {- const seed = mnemonicToSeedSync(KNOWN_MNEMONIC);- expect(deriveAesKeyFromSeed(seed)).toBe(- 'dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1',- );- });-});--describe('deriveEvmAddressFromMnemonic', () => {- it('returns a 0x-prefixed 42-character string', () => {- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- expect(address).toMatch(/^0x[0-9a-fA-F]{40}$/);- });-- it('is deterministic for the same mnemonic', () => {- const addr1 = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- const addr2 = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- expect(addr1).toBe(addr2);- });-- it('returns the well-known address for the all-abandon mnemonic', () => {- // MetaMask / BIP44 m/44'/60'/0'/0/0 for all-abandon is a stable known address.- // Pinned in EIP-55 checksummed form — validates both identity and checksum casing.- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- expect(address).toBe('0x9858EfFD232B4033E47d90003D41EC34EcaEda94');- });+ it('preserves the existing storage-key result for the canonical BIP-39 seed', () => {+ const seed = bytesFromHex(CANONICAL_SEED_HEX);- it('returns a different address for a different mnemonic', () => {- const other = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong';- const addrA = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- const addrB = deriveEvmAddressFromMnemonic(other);- expect(addrA).not.toBe(addrB);- });-- it('produces a checksummed address (EIP-55)', () => {- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);- // At least some characters must be uppercase (otherwise it would just be lowercase hex).- // EIP-55 checksummed addresses contain mixed case by design.- const hex = address.slice(2);- // Not all-lowercase and not all-uppercase → mixed casing applied.- const hasUpper = hex !== hex.toLowerCase();- const hasLower = hex !== hex.toUpperCase();- expect(hasUpper && hasLower).toBe(true);- });-});--describe('deriveBtcAddressFromMnemonic', () => {- it('returns the well-known address for the all-abandon mnemonic', () => {- expect(deriveBtcAddressFromMnemonic(KNOWN_MNEMONIC)).toBe('1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA');- });-});--describe('deriveSolanaAddressFromMnemonic', () => {- it('returns the well-known address for the all-abandon mnemonic', () => {- expect(deriveSolanaAddressFromMnemonic(KNOWN_MNEMONIC)).toBe(- 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk'+ expect(deriveAesKeyFromSeed(seed)).toBe(+ 'dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1');+ expect(seed).toEqual(new Uint8Array(64));});-});-describe('deriveTronAddressFromMnemonic', () => {- it('returns the well-known address for the all-abandon mnemonic', () => {- expect(deriveTronAddressFromMnemonic(KNOWN_MNEMONIC)).toBe(- 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH'- );- });-});+ it('rejects a non-BIP-39-sized seed and clears it', () => {+ const seed = new Uint8Array([1, 2, 3]);-describe('deriveWalletAccountsFromMnemonic', () => {- it('returns one derived identity per supported chain in a stable order', () => {- expect(deriveWalletAccountsFromMnemonic(KNOWN_MNEMONIC)).toEqual([- {- chain: 'evm',- address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',- derivationPath: "m/44'/60'/0'/0/0",- },- {- chain: 'btc',- address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',- derivationPath: "m/44'/0'/0'/0/0",- },- {- chain: 'solana',- address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',- derivationPath: "m/44'/501'/0'/0'",- },- {- chain: 'tron',- address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',- derivationPath: "m/44'/195'/0'/0/0",- },- ]);+ expect(() => deriveAesKeyFromSeed(seed)).toThrow(/exactly 64 bytes/i);+ expect(seed).toEqual(new Uint8Array(3));});});diff --git a/app/src/utils/cryptoKeys.ts b/app/src/utils/cryptoKeys.tsindex 5a40dba886..72908ea75f 100644--- a/app/src/utils/cryptoKeys.ts+++ b/app/src/utils/cryptoKeys.ts@@ -1,186 +1,24 @@-import { ed25519 } from '@noble/curves/ed25519.js';-import { hmac } from '@noble/hashes/hmac.js';-import { ripemd160 } from '@noble/hashes/legacy.js';import { pbkdf2 } from '@noble/hashes/pbkdf2.js';-import { sha256, sha512 } from '@noble/hashes/sha2.js';-import { keccak_256 } from '@noble/hashes/sha3.js';+import { sha256 } from '@noble/hashes/sha2.js';import { bytesToHex } from '@noble/hashes/utils.js';-import { getPublicKey } from '@noble/secp256k1';-import { base58 } from '@scure/base';-import { HDKey } from '@scure/bip32';-import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';-import { wordlist } from '@scure/bip39/wordlists/english.js';-/** Word count for newly generated recovery phrases (128-bit entropy, BIP39). */+/** Word count used when the wallet module generates a new recovery phrase. */export const MNEMONIC_GENERATE_WORD_COUNT = 12;-type WalletChain = 'evm' | 'btc' | 'solana' | 'tron';-export type WalletSetupSource = 'generated' | 'imported';--interface WalletAccountIdentity {- chain: WalletChain;- address: string;- derivationPath: string;-}--/**- * Generate a 12-word BIP39 mnemonic phrase (128-bit entropy).- */-export function generateMnemonicPhrase(): string {- return generateMnemonic(wordlist, 128);-}/**- * Validate a BIP39 mnemonic phrase.- */-export function validateMnemonicPhrase(mnemonic: string): boolean {- return validateMnemonic(mnemonic, wordlist);-}--/**- * Derive a 256-bit AES encryption key from a mnemonic phrase.- * Uses BIP39 seed derivation followed by PBKDF2-SHA256.- * Returns the key as a hex string.- */-export function deriveAesKeyFromMnemonic(mnemonic: string): string {- // Get the BIP39 seed (512-bit) from the mnemonic- const seed = mnemonicToSeedSync(mnemonic);-- return deriveAesKeyFromSeed(seed);-}--/**- * Derive the existing 256-bit local storage key from a BIP-39 seed.- *- * The wallet module owns phrase validation and seed derivation; this helper- * keeps only OpenHuman's generic storage-key KDF and its compatibility values.+ * Derive the existing 256-bit OpenHuman storage key from a module-derived+ * BIP-39 seed. The seed buffer is cleared after the generic storage KDF runs.*/export function deriveAesKeyFromSeed(seed: Uint8Array): string {- const salt = new TextEncoder().encode('openhuman-aes-key-v1');- const derivedKey = pbkdf2(sha256, seed, salt, { c: 100000, dkLen: 32 });-- return bytesToHex(derivedKey);-}--/** BIP44 path for first Ethereum account: m/44'/60'/0'/0/0 */-const EVM_DERIVATION_PATH = "m/44'/60'/0'/0/0";-const BTC_DERIVATION_PATH = "m/44'/0'/0'/0/0";-const SOLANA_DERIVATION_PATH = "m/44'/501'/0'/0'";-const TRON_DERIVATION_PATH = "m/44'/195'/0'/0/0";--/**- * Derive the first EVM wallet address (Ethereum BIP44) from a mnemonic phrase.- * Uses path m/44'/60'/0'/0/0. Returns a checksummed 0x-prefixed address.- */-export function deriveEvmAddressFromMnemonic(mnemonic: string): string {- const privateKey = deriveSecp256k1PrivateKey(mnemonic, EVM_DERIVATION_PATH);- // Ethereum address = keccak256(uncompressed public key without 0x04)[12:]- const pubKey = getPublicKey(privateKey, false); // uncompressed, 65 bytes- const hash = keccak_256(pubKey.slice(1));- const addressBytes = hash.slice(-20);- const hex = bytesToHex(addressBytes);- return toChecksumAddress('0x' + hex);-}--export function deriveBtcAddressFromMnemonic(mnemonic: string): string {- const privateKey = deriveSecp256k1PrivateKey(mnemonic, BTC_DERIVATION_PATH);- const compressedPublicKey = getPublicKey(privateKey, true);- const payload = new Uint8Array(21);- payload[0] = 0x00;- payload.set(ripemd160(sha256(compressedPublicKey)), 1);- return base58CheckEncode(payload);-}--export function deriveSolanaAddressFromMnemonic(mnemonic: string): string {- const seed = mnemonicToSeedSync(mnemonic);- const privateKey = deriveSlip10Ed25519PrivateKey(seed, SOLANA_DERIVATION_PATH);- return base58.encode(ed25519.getPublicKey(privateKey));-}--export function deriveTronAddressFromMnemonic(mnemonic: string): string {- const privateKey = deriveSecp256k1PrivateKey(mnemonic, TRON_DERIVATION_PATH);- const publicKey = getPublicKey(privateKey, false);- const payload = new Uint8Array(21);- payload[0] = 0x41;- payload.set(keccak_256(publicKey.slice(1)).slice(-20), 1);- return base58CheckEncode(payload);-}--export function deriveWalletAccountsFromMnemonic(mnemonic: string): WalletAccountIdentity[] {- return [- {- chain: 'evm',- address: deriveEvmAddressFromMnemonic(mnemonic),- derivationPath: EVM_DERIVATION_PATH,- },- {- chain: 'btc',- address: deriveBtcAddressFromMnemonic(mnemonic),- derivationPath: BTC_DERIVATION_PATH,- },- {- chain: 'solana',- address: deriveSolanaAddressFromMnemonic(mnemonic),- derivationPath: SOLANA_DERIVATION_PATH,- },- {- chain: 'tron',- address: deriveTronAddressFromMnemonic(mnemonic),- derivationPath: TRON_DERIVATION_PATH,- },- ];-}--/** Simple checksum: lowercase with 0x, then capitalize by hash. */-function toChecksumAddress(address: string): string {- const a = address.replace(/^0x/i, '').toLowerCase();- const hash = bytesToHex(keccak_256(new TextEncoder().encode(a)));- let result = '0x';- for (let i = 0; i < 40; i++) {- result += parseInt(hash[i], 16) >= 8 ? a[i].toUpperCase() : a[i];+ if (seed.length !== 64) {+ seed.fill(0);+ throw new Error('Recovery seed must be exactly 64 bytes.');}- return result;-}--function deriveSecp256k1PrivateKey(mnemonic: string, derivationPath: string): Uint8Array {- const seed = mnemonicToSeedSync(mnemonic);- const hdkey = HDKey.fromMasterSeed(seed);- const derived = hdkey.derive(derivationPath);- if (!derived.privateKey) {- throw new Error(`Failed to derive private key for path ${derivationPath}`);- }- return derived.privateKey;-}--function deriveSlip10Ed25519PrivateKey(seed: Uint8Array, derivationPath: string): Uint8Array {- let key = hmac(sha512, new TextEncoder().encode('ed25519 seed'), seed);- let privateKey = key.slice(0, 32);- let chainCode = key.slice(32);-- for (const segment of derivationPath.split('/').slice(1)) {- if (!segment.endsWith("'")) {- throw new Error(`Ed25519 derivation path must be fully hardened: ${derivationPath}`);- }- const index = Number.parseInt(segment.slice(0, -1), 10);- const hardened = (index + 0x80000000) >>> 0;- const data = new Uint8Array(37);- data[0] = 0;- data.set(privateKey, 1);- data[33] = (hardened >>> 24) & 0xff;- data[34] = (hardened >>> 16) & 0xff;- data[35] = (hardened >>> 8) & 0xff;- data[36] = hardened & 0xff;- key = hmac(sha512, chainCode, data);- privateKey = key.slice(0, 32);- chainCode = key.slice(32);+ const salt = new TextEncoder().encode('openhuman-aes-key-v1');+ try {+ const derivedKey = pbkdf2(sha256, seed, salt, { c: 100000, dkLen: 32 });+ return bytesToHex(derivedKey);+ } finally {+ seed.fill(0);}-- return privateKey;-}--function base58CheckEncode(payload: Uint8Array): string {- const checksum = sha256(sha256(payload)).slice(0, 4);- const bytes = new Uint8Array(payload.length + checksum.length);- bytes.set(payload, 0);- bytes.set(checksum, payload.length);- return base58.encode(bytes);}