@sidhujag/sysweb3-keyring 1.0.626 → 1.0.628

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/cjs/keyring-core.js +2512 -0
  3. package/cjs/keyring-core.js.map +1 -0
  4. package/cjs/keyring-manager.js +23 -2437
  5. package/cjs/keyring-manager.js.map +1 -1
  6. package/cjs/software.js +58 -0
  7. package/cjs/software.js.map +1 -0
  8. package/cjs/storage-core.js +227 -0
  9. package/cjs/storage-core.js.map +1 -0
  10. package/cjs/storage.js +15 -210
  11. package/cjs/storage.js.map +1 -1
  12. package/cjs/transactions/ethereum.js +121 -29
  13. package/cjs/transactions/ethereum.js.map +1 -1
  14. package/cjs/transactions/evm-local-signer.js +11 -1
  15. package/cjs/transactions/evm-local-signer.js.map +1 -1
  16. package/cjs/transactions/hardware-psbt.js +167 -0
  17. package/cjs/transactions/hardware-psbt.js.map +1 -0
  18. package/cjs/transactions/syscoin-core.js +651 -0
  19. package/cjs/transactions/syscoin-core.js.map +1 -0
  20. package/cjs/transactions/syscoin.js +8 -768
  21. package/cjs/transactions/syscoin.js.map +1 -1
  22. package/cjs/types.js.map +1 -1
  23. package/package.json +38 -4
  24. package/types/keyring-core.d.ts +257 -0
  25. package/types/keyring-manager.d.ts +5 -223
  26. package/types/software.d.ts +23 -0
  27. package/types/storage-core.d.ts +22 -0
  28. package/types/storage.d.ts +1 -4
  29. package/types/transactions/ethereum.d.ts +16 -6
  30. package/types/transactions/evm-local-signer.d.ts +3 -1
  31. package/types/transactions/hardware-psbt.d.ts +7 -0
  32. package/types/transactions/syscoin-core.d.ts +92 -0
  33. package/types/transactions/syscoin.d.ts +8 -67
  34. package/types/types.d.ts +10 -0
  35. package/cjs/transactions/__tests__/integration.test.js +0 -237
  36. package/cjs/transactions/__tests__/integration.test.js.map +0 -1
  37. package/cjs/transactions/__tests__/syscoin.test.js +0 -361
  38. package/cjs/transactions/__tests__/syscoin.test.js.map +0 -1
  39. package/types/transactions/__tests__/integration.test.d.ts +0 -1
  40. package/types/transactions/__tests__/syscoin.test.d.ts +0 -1
@@ -0,0 +1,2512 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.KeyringCore = void 0;
40
+ const secp256k1_1 = __importDefault(require("@bitcoinerlab/secp256k1"));
41
+ const sysweb3_network_1 = require("@sidhujag/sysweb3-network");
42
+ const bip32_1 = require("bip32");
43
+ const bs58check_1 = __importDefault(require("bs58check"));
44
+ const crypto_1 = __importDefault(require("crypto"));
45
+ const crypto_js_1 = __importDefault(require("crypto-js"));
46
+ const mapValues_1 = __importDefault(require("lodash/mapValues"));
47
+ const omit_1 = __importDefault(require("lodash/omit"));
48
+ const syscoinjs = __importStar(require("syscoinjs-lib"));
49
+ const BIP84 = __importStar(require("syscoinjs-lib/bip84-replacement"));
50
+ // Reference embedded bitcoinjs from syscoinjs-lib
51
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
+ const bjs = syscoinjs.utils.bitcoinjs;
53
+ const LEGACY_ENCRYPTION_KDF = 'pbkdf2-sha512-20000';
54
+ const SLH_DSA_DERIVATION_VERSION = 1;
55
+ // Preserve Pali v1 SLH derivation: first 32 bytes of the account-scoped HMAC.
56
+ // Pali expands this setup secret into the 48-byte SLH skSeed/skPrf/pkSeed tuple.
57
+ const SLH_DSA_SETUP_SECRET_HEX_LENGTH = 64;
58
+ const SLH_DSA_PARAMETER_SET = 'SLH-DSA-SHA2-128-24';
59
+ const ethers_v6_1 = require("./ethers-v6");
60
+ const initial_state_1 = require("./initial-state");
61
+ const private_records_1 = require("./private-records");
62
+ const signers_1 = require("./signers");
63
+ const storage_core_1 = require("./storage-core");
64
+ const ethereum_1 = require("./transactions/ethereum");
65
+ const evm_local_signer_1 = require("./transactions/evm-local-signer");
66
+ const syscoin_core_1 = require("./transactions/syscoin-core");
67
+ const types_1 = require("./types");
68
+ const blockbook_cache_1 = require("./utils/blockbook-cache");
69
+ const derivation_paths_1 = require("./utils/derivation-paths");
70
+ const psbt_account_scope_1 = require("./utils/psbt-account-scope");
71
+ const watch_descriptor_1 = require("./utils/watch-descriptor");
72
+ // Dynamic ETH HD path generation - will be computed as needed
73
+ /**
74
+ * Secure Buffer implementation for sensitive data
75
+ * Provides explicit memory clearing capability
76
+ */
77
+ class SecureBuffer {
78
+ constructor(data) {
79
+ this._isCleared = false;
80
+ if (typeof data === 'string') {
81
+ this.buffer = Buffer.from(data, 'utf8');
82
+ }
83
+ else {
84
+ this.buffer = Buffer.from(data);
85
+ }
86
+ }
87
+ get() {
88
+ if (this._isCleared || !this.buffer) {
89
+ throw new Error('SecureBuffer has been cleared');
90
+ }
91
+ return Buffer.from(this.buffer); // Return copy
92
+ }
93
+ toString() {
94
+ if (this._isCleared || !this.buffer) {
95
+ throw new Error('SecureBuffer has been cleared');
96
+ }
97
+ return this.buffer.toString('utf8');
98
+ }
99
+ clear() {
100
+ if (!this._isCleared && this.buffer) {
101
+ // Zeroing must not depend on a working platform random source.
102
+ this.buffer.fill(0);
103
+ this.buffer = null;
104
+ this._isCleared = true;
105
+ }
106
+ }
107
+ isCleared() {
108
+ return this._isCleared;
109
+ }
110
+ }
111
+ class KeyringCore {
112
+ constructor(dependencies) {
113
+ // Store getter function for accessing Redux state
114
+ this.getVaultState = null;
115
+ // Method to inject store getter from Pali side
116
+ this.setVaultStateGetter = (getter) => {
117
+ this.getVaultState = getter;
118
+ };
119
+ // Helper method to get current vault state
120
+ this.getVault = () => {
121
+ if (!this.getVaultState) {
122
+ throw new Error('Vault state getter not configured. Call setVaultStateGetter() first.');
123
+ }
124
+ const vault = this.getVaultState();
125
+ // DEFENSIVE CHECK: Ensure vault state is properly structured
126
+ if (!vault) {
127
+ throw new Error('Vault state is undefined. Ensure Redux store is properly initialized with vault state.');
128
+ }
129
+ if (!vault.activeNetwork) {
130
+ throw new Error('Vault state is missing activeNetwork. Ensure vault state is properly initialized before keyring operations.');
131
+ }
132
+ if (!vault.activeAccount) {
133
+ throw new Error('Vault state is missing activeAccount. Ensure vault state is properly initialized before keyring operations.');
134
+ }
135
+ return vault;
136
+ };
137
+ // Helper to get active chain from vault state (replaces this.activeChain)
138
+ this.getActiveChain = () => {
139
+ return this.getVault().activeNetwork.kind;
140
+ };
141
+ this.accountAddressExists = (accounts, address, caseInsensitive = false) => {
142
+ const expectedAddress = caseInsensitive ? address.toLowerCase() : address;
143
+ return Object.values(accounts || {}).some((accountsByType) => Object.values(accountsByType || {}).some((account) => {
144
+ if (!account?.address) {
145
+ return false;
146
+ }
147
+ const accountAddress = caseInsensitive
148
+ ? account.address.toLowerCase()
149
+ : account.address;
150
+ return accountAddress === expectedAddress;
151
+ }));
152
+ };
153
+ // Secure session data - using Buffers that can be explicitly cleared
154
+ this.sessionPassword = null;
155
+ this.sessionMnemonic = null; // can be a mnemonic or a zprv, can be changed to a zprv when using an imported wallet
156
+ this.privateRecordSessionRevision = 0;
157
+ this.createSyscoinTransactions = () => new syscoin_core_1.SyscoinTransactionsCore(this.getSigner, this.getReadOnlySigner, this.getAccountsState, this.getAddress, this.syscoinHardwareSigners, this.capturePsbtSigningContext);
158
+ this.requireLedgerSigner = () => {
159
+ if (!this.ledgerSigner)
160
+ throw (0, syscoin_core_1.createHardwareSignerUnavailableError)('Ledger');
161
+ return this.ledgerSigner;
162
+ };
163
+ this.requireTrezorSigner = () => {
164
+ if (!this.trezorSigner)
165
+ throw (0, syscoin_core_1.createHardwareSignerUnavailableError)('Trezor');
166
+ return this.trezorSigner;
167
+ };
168
+ // ===================================== PUBLIC METHODS - KEYRING MANAGER FOR HD - SYS ALL ===================================== //
169
+ this.setStorage = (client) => {
170
+ if (!this.storage.setClient) {
171
+ throw new Error('Storage replacement is unavailable in this host');
172
+ }
173
+ this.storage.setClient(client);
174
+ };
175
+ this.validateAccountType = (account) => {
176
+ return account.isImported === true
177
+ ? types_1.KeyringAccountType.Imported
178
+ : types_1.KeyringAccountType.HDAccount;
179
+ };
180
+ this.isUnlocked = () => !!this.sessionPassword && !this.sessionPassword.isCleared();
181
+ this.lockWallet = async () => {
182
+ this.privateRecordSessionRevision++;
183
+ // Clear secure session data
184
+ if (this.sessionPassword) {
185
+ this.sessionPassword.clear();
186
+ this.sessionPassword = null;
187
+ }
188
+ if (this.sessionMnemonic) {
189
+ this.sessionMnemonic.clear();
190
+ this.sessionMnemonic = null;
191
+ }
192
+ // Clear transaction handlers that may hold HD signers
193
+ if (this.syscoinTransaction) {
194
+ // Replace with empty object to clear references
195
+ this.syscoinTransaction = {};
196
+ }
197
+ // NOTE: We intentionally don't clear ethereumTransaction here because
198
+ // polling needs the web3Provider even when the wallet is locked.
199
+ // Clean up hardware wallet connections (await to ensure HID is released)
200
+ if (this.ledgerSigner) {
201
+ try {
202
+ await this.ledgerSigner.destroy();
203
+ }
204
+ catch (_) {
205
+ // ignore
206
+ }
207
+ }
208
+ if (this.trezorSigner) {
209
+ try {
210
+ await this.trezorSigner.destroy();
211
+ }
212
+ catch (_) {
213
+ // ignore
214
+ }
215
+ }
216
+ };
217
+ // Direct secure transfer of session data to another keyring
218
+ this.transferSessionTo = (targetKeyring) => {
219
+ if (!this.isUnlocked()) {
220
+ throw new Error('Source keyring must be unlocked to transfer session');
221
+ }
222
+ // Cross-wallet transfers must fail before either keyring's buffers change.
223
+ if (!(targetKeyring instanceof KeyringCore) ||
224
+ targetKeyring.authority !== this.authority ||
225
+ targetKeyring.storage !== this.storage ||
226
+ targetKeyring.vaultPersistence !== this.vaultPersistence) {
227
+ throw new Error('Cannot transfer session between different wallet authorities');
228
+ }
229
+ if (targetKeyring === this)
230
+ return;
231
+ // Transfer ownership of our buffers to the target
232
+ if (!this.sessionPassword || !this.sessionMnemonic) {
233
+ throw new Error('Session data is missing during transfer');
234
+ }
235
+ this.privateRecordSessionRevision++;
236
+ targetKeyring.acceptSessionFrom(this);
237
+ // Null out our references (do NOT clear buffers - target owns them now)
238
+ this.sessionPassword = null;
239
+ this.sessionMnemonic = null;
240
+ };
241
+ // The checked transfer path never dispatches through a public host receiver.
242
+ this.acceptSessionFrom = (source) => {
243
+ if (source.authority !== this.authority ||
244
+ source.storage !== this.storage ||
245
+ source.vaultPersistence !== this.vaultPersistence) {
246
+ throw new Error('Cannot transfer session between different wallet authorities');
247
+ }
248
+ if (!source.sessionPassword || !source.sessionMnemonic) {
249
+ throw new Error('Session data is missing during transfer');
250
+ }
251
+ this.replaceSessionBuffers(source.sessionPassword, source.sessionMnemonic);
252
+ };
253
+ // Legacy trusted-host API. SoftwareKeyring disables direct buffer injection.
254
+ this.receiveSessionOwnership = (sessionPassword, sessionMnemonic) => this.replaceSessionBuffers(sessionPassword, sessionMnemonic);
255
+ this.replaceSessionBuffers = (sessionPassword, sessionMnemonic) => {
256
+ this.privateRecordSessionRevision++;
257
+ // Clear any existing data first
258
+ if (this.sessionPassword) {
259
+ this.sessionPassword.clear();
260
+ }
261
+ if (this.sessionMnemonic) {
262
+ this.sessionMnemonic.clear();
263
+ }
264
+ // Take ownership of the actual SecureBuffer objects
265
+ // No copying - these are the original objects
266
+ this.sessionPassword = sessionPassword;
267
+ this.sessionMnemonic = sessionMnemonic;
268
+ };
269
+ this.addNewAccount = async (label) => {
270
+ // Check if wallet is unlocked
271
+ if (!this.isUnlocked()) {
272
+ throw new Error('Wallet must be unlocked to add new accounts');
273
+ }
274
+ // addNewAccount should only create accounts from the main seed
275
+ // For importing accounts (including zprvs), use importAccount
276
+ if (this.getActiveChain() === sysweb3_network_1.INetworkType.Syscoin) {
277
+ return await this.addNewAccountToSyscoinChain(label);
278
+ }
279
+ else {
280
+ // EVM chainType
281
+ return await this.addNewAccountToEth(label);
282
+ }
283
+ };
284
+ this.createSmartAccount = async ({ address, deriveAccount, label, metadata, }) => {
285
+ const vault = this.getVault();
286
+ const { accounts } = vault;
287
+ const smartAccounts = accounts[types_1.KeyringAccountType.SmartAccount] || {};
288
+ const nextId = this.getNextAccountId(smartAccounts);
289
+ const derived = deriveAccount
290
+ ? await deriveAccount(nextId)
291
+ : { address, metadata };
292
+ if (!derived.address) {
293
+ throw new Error('Smart account address is required');
294
+ }
295
+ if (this.accountAddressExists(accounts, derived.address, true)) {
296
+ throw new Error('Account already exists on your Wallet.');
297
+ }
298
+ return {
299
+ address: derived.address,
300
+ balances: {
301
+ [sysweb3_network_1.INetworkType.Syscoin]: 0,
302
+ [sysweb3_network_1.INetworkType.Ethereum]: 0,
303
+ },
304
+ id: nextId,
305
+ isImported: false,
306
+ isLedgerWallet: false,
307
+ isSmartAccount: true,
308
+ isTrezorWallet: false,
309
+ label: label || `Smart Account ${nextId + 1}`,
310
+ smartAccount: derived.metadata,
311
+ xprv: '',
312
+ xpub: derived.address,
313
+ };
314
+ };
315
+ this.getNewChangeAddress = async () => {
316
+ const vault = this.getVault();
317
+ const { accounts, activeAccount } = vault;
318
+ const account = accounts[activeAccount.type]?.[activeAccount.id];
319
+ if (!account) {
320
+ throw new Error('Active account not found');
321
+ }
322
+ const { xpub, isImported, address } = account;
323
+ // For imported single-address accounts, always return the single address
324
+ const looksLikeSingleAddress = isImported &&
325
+ xpub === address &&
326
+ !this.isDescriptor(xpub) &&
327
+ !this.isXpubLike(xpub);
328
+ if (looksLikeSingleAddress)
329
+ return address;
330
+ return await this.getAddress(xpub, true); // Don't skip increment - get next unused
331
+ };
332
+ this.getChangeAddress = async (id) => {
333
+ const vault = this.getVault();
334
+ const { accounts, activeAccount } = vault;
335
+ const account = accounts[activeAccount.type]?.[id];
336
+ if (!account) {
337
+ throw new Error(`Account with id ${id} not found`);
338
+ }
339
+ const { xpub, isImported, address } = account;
340
+ if (isImported &&
341
+ xpub === address &&
342
+ !this.isDescriptor(xpub) &&
343
+ !this.isXpubLike(xpub))
344
+ return address;
345
+ return await this.getAddress(xpub, true);
346
+ };
347
+ this.getPubkey = async (id, isChangeAddress) => {
348
+ const vault = this.getVault();
349
+ const { accounts, activeAccount } = vault;
350
+ const account = accounts[activeAccount.type]?.[id];
351
+ if (!account) {
352
+ throw new Error(`Account with id ${id} not found`);
353
+ }
354
+ const { xpub, isImported, address } = account;
355
+ // Guard: single-address imported are watch-only
356
+ if (isImported && xpub === address) {
357
+ throw new Error('Public key not available for single-address imported accounts');
358
+ }
359
+ // Guard: descriptor/xpub watch-only (no xprv and not hardware)
360
+ if (this.isWatchOnlyAccount(account)) {
361
+ throw new Error('Public key not available for watch-only accounts');
362
+ }
363
+ return await this.getCurrentAddressPubkey(xpub, isChangeAddress);
364
+ };
365
+ this.getBip32Path = async (id, isChangeAddress) => {
366
+ const vault = this.getVault();
367
+ const { accounts, activeAccount } = vault;
368
+ const account = accounts[activeAccount.type]?.[id];
369
+ if (!account) {
370
+ throw new Error(`Account with id ${id} not found`);
371
+ }
372
+ const { xpub, isImported, address } = account;
373
+ // Guard: single-address imported are watch-only
374
+ if (isImported && xpub === address) {
375
+ throw new Error('BIP32 path not available for single-address imported accounts');
376
+ }
377
+ // Guard: descriptor/xpub watch-only (no xprv and not hardware)
378
+ if (this.isWatchOnlyAccount(account)) {
379
+ throw new Error('BIP32 path not available for watch-only accounts');
380
+ }
381
+ return await this.getCurrentAddressBip32Path(xpub, isChangeAddress);
382
+ };
383
+ this.updateReceivingAddress = async () => {
384
+ const vault = this.getVault();
385
+ const { accounts, activeAccount } = vault;
386
+ const account = accounts[activeAccount.type]?.[activeAccount.id];
387
+ if (!account) {
388
+ throw new Error('Active account not found');
389
+ }
390
+ const { xpub, isImported, address } = account;
391
+ if (isImported &&
392
+ xpub === address &&
393
+ !this.isDescriptor(xpub) &&
394
+ !this.isXpubLike(xpub))
395
+ return address;
396
+ const nextAddress = await this.getAddress(xpub, false);
397
+ // NOTE: Address updates should be dispatched to Redux store, not updated here
398
+ // The calling code should handle the Redux dispatch
399
+ return nextAddress;
400
+ };
401
+ this.getAccountById = (id, accountType) => {
402
+ const vault = this.getVault();
403
+ const accounts = vault.accounts[accountType];
404
+ const account = accounts[id];
405
+ if (!account) {
406
+ throw new Error('Account not found');
407
+ }
408
+ return (0, omit_1.default)(account, 'xprv');
409
+ };
410
+ this.getPrivateKeyByAccountId = async (id, accountType, pwd) => {
411
+ try {
412
+ // Validate password using vault salt (same pattern as getSeed)
413
+ if (!this.sessionPassword) {
414
+ throw new Error('Unlock wallet first');
415
+ }
416
+ // Get vault salt for password validation
417
+ const vaultKeys = await this.storage.get('vault-keys');
418
+ if (!vaultKeys || !vaultKeys.salt) {
419
+ throw new Error('Vault keys not found');
420
+ }
421
+ const genPwd = await this.deriveStoredSessionKey(pwd, vaultKeys);
422
+ if (this.getSessionPasswordString() !== genPwd) {
423
+ throw new Error('Invalid password');
424
+ }
425
+ const vault = this.getVault();
426
+ const account = vault.accounts[accountType][id];
427
+ if (!account) {
428
+ throw new Error('Account not found');
429
+ }
430
+ // Decrypt the stored private key using secure method
431
+ const decryptedPrivateKey = this.withSecureData((sessionPwd) => {
432
+ const decrypted = crypto_js_1.default.AES.decrypt(account.xprv, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
433
+ if (!decrypted) {
434
+ throw new Error('Failed to decrypt private key. Invalid password or corrupted data.');
435
+ }
436
+ return decrypted;
437
+ });
438
+ // NOTE: Returning decrypted private key as string is necessary for compatibility
439
+ // Callers should handle this sensitive data carefully
440
+ return decryptedPrivateKey;
441
+ }
442
+ catch (error) {
443
+ this.validateAndHandleErrorByMessage(error.message);
444
+ throw error;
445
+ }
446
+ };
447
+ this.getActiveAccount = () => {
448
+ const vault = this.getVault();
449
+ const { accounts, activeAccount } = vault;
450
+ const activeAccountId = activeAccount.id;
451
+ const activeAccountType = activeAccount.type;
452
+ return {
453
+ activeAccount: (0, omit_1.default)(accounts[activeAccountType][activeAccountId], 'xprv'),
454
+ activeAccountType,
455
+ };
456
+ };
457
+ this.isDescriptor = (s) => /^(addr|pkh|wpkh|sh|wsh|tr|combo|multi|sortedmulti)\s*\(/i.test(s || '');
458
+ this.isXpubLike = (s) => /^(xpub|tpub|zpub|vpub)/i.test(s || '');
459
+ this.getEncryptedXprv = (hd) => {
460
+ return this.withSecureData((sessionPwd) => {
461
+ return crypto_js_1.default.AES.encrypt(this.getSysActivePrivateKey(hd), sessionPwd).toString();
462
+ });
463
+ };
464
+ this.getSeed = async (pwd) => {
465
+ if (!this.sessionPassword) {
466
+ throw new Error('Unlock wallet first');
467
+ }
468
+ // Get vault salt for password validation (consistent with getPrivateKeyByAccountId)
469
+ const vaultKeys = await this.storage.get('vault-keys');
470
+ if (!vaultKeys || !vaultKeys.salt) {
471
+ throw new Error('Vault keys not found');
472
+ }
473
+ const genPwd = await this.deriveStoredSessionKey(pwd, vaultKeys);
474
+ if (this.getSessionPasswordString() !== genPwd) {
475
+ throw new Error('Invalid password');
476
+ }
477
+ // v4 vault is encrypted with the derived session password key (PBKDF2 output)
478
+ let { mnemonic } = await this.vaultPersistence.getDecryptedVault(genPwd);
479
+ if (!mnemonic) {
480
+ throw new Error('Mnemonic not found in vault or is empty');
481
+ }
482
+ // Try to detect if mnemonic is encrypted or plain text
483
+ const isLikelyPlainMnemonic = mnemonic.includes(' ') &&
484
+ (mnemonic.split(' ').length === 12 || mnemonic.split(' ').length === 24);
485
+ if (!isLikelyPlainMnemonic) {
486
+ try {
487
+ mnemonic = crypto_js_1.default.AES.decrypt(mnemonic, pwd).toString(crypto_js_1.default.enc.Utf8);
488
+ }
489
+ catch (decryptError) {
490
+ // If decryption fails, assume mnemonic is already decrypted
491
+ console.warn('Mnemonic decryption failed in getSeed, using as-is:', decryptError.message);
492
+ }
493
+ }
494
+ if (!mnemonic) {
495
+ throw new Error('Failed to decrypt mnemonic or mnemonic is empty after decryption');
496
+ }
497
+ return mnemonic;
498
+ };
499
+ this.deriveSLHDSASetupSecretForAccount = async ({ accountIndex, }) => {
500
+ if (!this.sessionPassword) {
501
+ throw new Error('Unlock wallet first');
502
+ }
503
+ const mnemonic = this.getDecryptedMnemonic();
504
+ const normalizedMnemonic = mnemonic.normalize('NFKD');
505
+ const seed = crypto_js_1.default.PBKDF2(normalizedMnemonic, `mnemonic`.normalize('NFKD'), {
506
+ hasher: crypto_js_1.default.algo.SHA512,
507
+ iterations: 2048,
508
+ keySize: 512 / 32,
509
+ });
510
+ const derivationLabel = `PALI/${SLH_DSA_PARAMETER_SET}/v${SLH_DSA_DERIVATION_VERSION}/account/${accountIndex}`;
511
+ const digest = crypto_js_1.default.HmacSHA512(derivationLabel, crypto_js_1.default.enc.Hex.parse(seed.toString(crypto_js_1.default.enc.Hex)));
512
+ return {
513
+ derivationLabel,
514
+ setupSecretHex: digest
515
+ .toString(crypto_js_1.default.enc.Hex)
516
+ .slice(0, SLH_DSA_SETUP_SECRET_HEX_LENGTH),
517
+ };
518
+ };
519
+ this.encryptSLHDSASessionState = (plainText) => {
520
+ return this.withSecureData((sessionPwd) => crypto_js_1.default.AES.encrypt(plainText, sessionPwd).toString());
521
+ };
522
+ this.decryptSLHDSASessionState = (cipherText) => {
523
+ return this.withSecureData((sessionPwd) => {
524
+ const plainText = crypto_js_1.default.AES.decrypt(cipherText, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
525
+ if (!plainText) {
526
+ throw new Error('Failed to decrypt SLH-DSA session state');
527
+ }
528
+ return plainText;
529
+ });
530
+ };
531
+ this.setSignerNetwork = async (network) => {
532
+ // With multi-keyring architecture, each keyring is dedicated to specific slip44
533
+ if (sysweb3_network_1.INetworkType.Ethereum !== network.kind &&
534
+ sysweb3_network_1.INetworkType.Syscoin !== network.kind) {
535
+ throw new Error('Unsupported chain');
536
+ }
537
+ // Validate network/chain type compatibility
538
+ if (network.kind === sysweb3_network_1.INetworkType.Ethereum &&
539
+ this.getActiveChain() === sysweb3_network_1.INetworkType.Syscoin) {
540
+ throw new Error('Cannot use Ethereum chain type with Syscoin network');
541
+ }
542
+ if (network.kind === sysweb3_network_1.INetworkType.Syscoin &&
543
+ this.getActiveChain() === sysweb3_network_1.INetworkType.Ethereum) {
544
+ throw new Error('Cannot use Syscoin chain type with Ethereum network');
545
+ }
546
+ // CRITICAL: Prevent UTXO-to-UTXO network switching within same keyring
547
+ // Each UTXO network should have its own KeyringManager instance based on slip44
548
+ const vault = this.getVault();
549
+ if (this.getActiveChain() === sysweb3_network_1.INetworkType.Syscoin && vault.activeNetwork) {
550
+ const currentSlip44 = vault.activeNetwork.slip44;
551
+ const newSlip44 = network.slip44;
552
+ if (currentSlip44 !== newSlip44) {
553
+ throw new Error(`Cannot switch between different UTXO networks within the same keyring. ` +
554
+ `Current network uses slip44=${currentSlip44}, target network uses slip44=${newSlip44}. ` +
555
+ `Each UTXO network requires a separate KeyringManager instance.`);
556
+ }
557
+ }
558
+ try {
559
+ // With multi-keyring architecture:
560
+ // - UTXO: Each keyring is dedicated to one network (slip44), so this is only called during initialization
561
+ // - EVM: All EVM networks share slip44=60, so network can change within the same keyring
562
+ if (network.kind === sysweb3_network_1.INetworkType.Syscoin) {
563
+ // For UTXO networks: validate that active account exists (accounts should be created via addNewAccount/initialize)
564
+ const accountId = vault.activeAccount.id || 0;
565
+ const accountType = vault.activeAccount.type || types_1.KeyringAccountType.HDAccount;
566
+ const accounts = vault.accounts[accountType];
567
+ if (!accounts[accountId] || !accounts[accountId].xpub) {
568
+ throw new Error(`Active account ${accountType}:${accountId} does not exist. Create accounts using addNewAccount() or initializeWalletSecurely() first.`);
569
+ }
570
+ // No additional setup needed - on-demand signers will be created when needed
571
+ }
572
+ else if (network.kind === sysweb3_network_1.INetworkType.Ethereum) {
573
+ // For EVM networks: we primarily need a correct provider for the active network.
574
+ // Active account validation can be temporarily inconsistent during network switching
575
+ // (e.g., placeholder activeAccount like Trezor:0 before accounts hydrate), and provider
576
+ // setup does not depend on it. So treat missing active account as a warning, not a hard error.
577
+ const accountId = vault.activeAccount.id || 0;
578
+ const accountType = vault.activeAccount.type || types_1.KeyringAccountType.HDAccount;
579
+ const accounts = vault.accounts[accountType];
580
+ if (!accounts?.[accountId]) {
581
+ console.warn(`[KeyringManager] Active account ${accountType}:${accountId} not found while setting EVM network; continuing to set provider`);
582
+ }
583
+ // Set up EVM provider for network switching
584
+ await this.setSignerEVM(network);
585
+ }
586
+ return {
587
+ success: true,
588
+ };
589
+ }
590
+ catch (err) {
591
+ console.log('ERROR setSignerNetwork', {
592
+ err,
593
+ });
594
+ this.validateAndHandleErrorByMessage(err.message);
595
+ //Rollback to previous values
596
+ console.error('Set Signer Network failed with', err);
597
+ return { success: false };
598
+ }
599
+ };
600
+ this.forgetMainWallet = async (pwd) => {
601
+ const vaultKeys = await this.storage.get('vault-keys');
602
+ if (!vaultKeys || !vaultKeys.salt) {
603
+ throw new Error('Vault keys not found');
604
+ }
605
+ const genPwd = await this.deriveStoredSessionKey(pwd, vaultKeys);
606
+ if (!this.sessionPassword) {
607
+ throw new Error('Unlock wallet first');
608
+ }
609
+ else if (this.getSessionPasswordString() !== genPwd) {
610
+ throw new Error('Invalid password');
611
+ }
612
+ await this.clearTemporaryLocalKeys();
613
+ };
614
+ this.importWeb3Account = (mnemonicOrPrivKey) => {
615
+ // Check if it's a hex string (Ethereum private key)
616
+ if ((0, ethers_v6_1.isHexString)(mnemonicOrPrivKey)) {
617
+ return (0, evm_local_signer_1.privateKeyToAccount)(mnemonicOrPrivKey);
618
+ }
619
+ // Check if it's a zprv/tprv (Syscoin private key)
620
+ const zprvPrefixes = ['zprv', 'tprv', 'vprv', 'xprv'];
621
+ if (zprvPrefixes.some((prefix) => mnemonicOrPrivKey.startsWith(prefix))) {
622
+ throw new Error('Syscoin extended private keys (zprv/tprv) should be imported using importAccount, not importWeb3Account');
623
+ }
624
+ // Otherwise, assume it's a mnemonic
625
+ return (0, evm_local_signer_1.deriveEvmAccountFromMnemonic)(mnemonicOrPrivKey, (0, derivation_paths_1.getAddressDerivationPath)('eth', 60, 0, false, 0));
626
+ };
627
+ this.getAccountXpub = () => {
628
+ const vault = this.getVault();
629
+ const { activeAccount } = vault;
630
+ const account = vault.accounts[activeAccount.type]?.[activeAccount.id];
631
+ if (!account) {
632
+ throw new Error('Active account not found');
633
+ }
634
+ return account.xpub;
635
+ };
636
+ this.isSeedValid = (seedPhrase) => BIP84.validateMnemonic(seedPhrase);
637
+ this.createNewSeed = (wordCount) => {
638
+ // Map BIP39 word counts to entropy strength
639
+ const wordCountToStrength = {
640
+ 12: 128,
641
+ 15: 160,
642
+ 18: 192,
643
+ 21: 224,
644
+ 24: 256,
645
+ };
646
+ const strength = wordCount ? wordCountToStrength[wordCount] : 128;
647
+ return strength
648
+ ? BIP84.generateMnemonic(strength)
649
+ : BIP84.generateMnemonic();
650
+ };
651
+ this.getUTXOState = () => {
652
+ const vault = this.getVault();
653
+ if (vault.activeNetwork.kind !== sysweb3_network_1.INetworkType.Syscoin) {
654
+ throw new Error('Cannot get state in a ethereum network');
655
+ }
656
+ const utxOAccounts = (0, mapValues_1.default)(vault.accounts.HDAccount, (value) => (0, omit_1.default)(value, 'xprv'));
657
+ return {
658
+ ...vault,
659
+ accounts: {
660
+ [types_1.KeyringAccountType.HDAccount]: utxOAccounts,
661
+ [types_1.KeyringAccountType.Imported]: {},
662
+ [types_1.KeyringAccountType.Trezor]: {},
663
+ [types_1.KeyringAccountType.Ledger]: {},
664
+ },
665
+ };
666
+ };
667
+ this.getActiveUTXOAccountState = () => {
668
+ const vault = this.getVault();
669
+ const { activeAccount } = vault;
670
+ return {
671
+ ...vault.accounts.HDAccount[activeAccount.id],
672
+ xprv: undefined,
673
+ };
674
+ };
675
+ this.getNetwork = () => this.getVault().activeNetwork;
676
+ this.createEthAccount = (privateKey) => (0, evm_local_signer_1.privateKeyToAccount)(privateKey);
677
+ // Helper to get current account data from backend
678
+ this.fetchCurrentAccountData = async (xpub, isChangeAddress) => {
679
+ const vault = this.getVault();
680
+ const { activeNetwork } = vault;
681
+ // Use read-only signer for backend calls - works for all account types including hardware wallets
682
+ const { main } = this.getReadOnlySigner();
683
+ const options = 'tokens=used&details=tokens';
684
+ // In-flight deduplicated: concurrent callers within a send flow
685
+ // (fee estimation, PSBT creation, signing) share a single request
686
+ const { tokens } = await (0, blockbook_cache_1.fetchBackendAccountCached)(main.blockbookURL, xpub, options);
687
+ const { receivingIndex, changeIndex } = this.setLatestIndexesFromXPubTokens(tokens);
688
+ // Get network configuration for BIP84 using network-provided pub type macros
689
+ const networkConfig = (0, sysweb3_network_1.getNetworkConfig)(activeNetwork.slip44, activeNetwork.currency);
690
+ const pubTypes = networkConfig?.types?.zPubType;
691
+ if (!pubTypes) {
692
+ throw new Error('Missing zPubType in network configuration');
693
+ }
694
+ const networks = networkConfig.networks;
695
+ const currentAccount = new BIP84.fromZPub(xpub, pubTypes, networks);
696
+ const addressIndex = isChangeAddress ? changeIndex : receivingIndex;
697
+ return {
698
+ currentAccount,
699
+ addressIndex,
700
+ main,
701
+ };
702
+ };
703
+ this.getAddress = async (xpub, isChangeAddress, options) => {
704
+ if (this.isDescriptor(xpub)) {
705
+ // The BIP84 history scanner below cannot choose a descriptor's next
706
+ // unused index. Import can derive index zero locally, but rotation must
707
+ // not reinterpret a descriptor as a BIP84 extended key.
708
+ if (!options?.forceIndex0) {
709
+ throw new Error('Address rotation is not supported for watch-only descriptors');
710
+ }
711
+ return (0, watch_descriptor_1.deriveDescriptorAddress)(xpub, this.getVault().activeNetwork, {
712
+ change: isChangeAddress,
713
+ });
714
+ }
715
+ const { currentAccount, addressIndex } = await this.fetchCurrentAccountData(xpub, isChangeAddress);
716
+ const effectiveIndex = options?.forceIndex0 ? 0 : addressIndex;
717
+ const address = currentAccount.getAddress(effectiveIndex, isChangeAddress, 84);
718
+ return address;
719
+ };
720
+ this.getCurrentAddressPubkey = async (xpub, isChangeAddress) => {
721
+ const { currentAccount, addressIndex } = await this.fetchCurrentAccountData(xpub, isChangeAddress);
722
+ // BIP84 returns the public key as a hex string directly
723
+ return currentAccount.getPublicKey(addressIndex, isChangeAddress);
724
+ };
725
+ this.getCurrentAddressBip32Path = async (xpub, isChangeAddress) => {
726
+ const vault = this.getVault();
727
+ const { activeAccount, activeNetwork } = vault;
728
+ const { addressIndex } = await this.fetchCurrentAccountData(xpub, isChangeAddress);
729
+ // Use the utility function to generate the proper derivation path
730
+ const coinShortcut = activeNetwork.currency.toLowerCase(); // e.g., 'sys', 'btc'
731
+ const path = (0, derivation_paths_1.getAddressDerivationPath)(coinShortcut, activeNetwork.slip44, activeAccount.id, isChangeAddress, addressIndex);
732
+ return path;
733
+ };
734
+ this.logout = () => {
735
+ this.lockWallet();
736
+ };
737
+ /**
738
+ * PRIVATE METHODS
739
+ */
740
+ // ===================================== AUXILIARY METHOD - FOR TRANSACTIONS CLASSES ===================================== //
741
+ this.getDecryptedPrivateKey = (targetAccount) => {
742
+ try {
743
+ const vault = this.getVault();
744
+ const { accounts } = vault;
745
+ const activeAccount = targetAccount || vault.activeAccount;
746
+ const activeAccountId = activeAccount.id;
747
+ const activeAccountType = activeAccount.type;
748
+ const isLedger = activeAccountType === types_1.KeyringAccountType.Ledger;
749
+ const isTrezor = activeAccountType === types_1.KeyringAccountType.Trezor;
750
+ const isHardwareWallet = isTrezor || isLedger;
751
+ if (!this.sessionPassword)
752
+ throw new Error('Wallet is locked cant proceed with transaction');
753
+ const activeAccountData = accounts[activeAccountType][activeAccountId];
754
+ if (!activeAccountData) {
755
+ throw new Error(`Active account (${activeAccountType}:${activeAccountId}) not found. Account switching may be in progress.`);
756
+ }
757
+ const { xprv, address } = activeAccountData;
758
+ if (isLedger || activeAccountData.isLedgerWallet)
759
+ this.requireLedgerSigner();
760
+ if (isTrezor || activeAccountData.isTrezorWallet)
761
+ this.requireTrezorSigner();
762
+ if (isHardwareWallet) {
763
+ return {
764
+ address,
765
+ decryptedPrivateKey: '',
766
+ };
767
+ }
768
+ if (!xprv) {
769
+ throw new Error(`Private key not found for account ${activeAccountType}:${activeAccountId}. Account may not be fully initialized.`);
770
+ }
771
+ let decryptedPrivateKey;
772
+ try {
773
+ decryptedPrivateKey = this.withSecureData((sessionPwd) => {
774
+ return crypto_js_1.default.AES.decrypt(xprv, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
775
+ });
776
+ }
777
+ catch (decryptError) {
778
+ throw new Error(`Failed to decrypt private key for account ${activeAccountType}:${activeAccountId}. The wallet may be locked or corrupted.`);
779
+ }
780
+ if (!decryptedPrivateKey) {
781
+ throw new Error(`Decrypted private key is empty for account ${activeAccountType}:${activeAccountId}. Invalid password or corrupted data.`);
782
+ }
783
+ // For EVM accounts, validate that the derived address matches the stored address
784
+ // This helps catch account switching race conditions early
785
+ if (this.getActiveChain() === sysweb3_network_1.INetworkType.Ethereum) {
786
+ try {
787
+ const derivedAccount = (0, evm_local_signer_1.privateKeyToAccount)(decryptedPrivateKey);
788
+ if (derivedAccount.address.toLowerCase() !== address.toLowerCase()) {
789
+ throw new Error(`Address mismatch for account ${activeAccountType}:${activeAccountId}. Expected ${address} but derived ${derivedAccount.address}. Account switching may be in progress.`);
790
+ }
791
+ }
792
+ catch (addressError) {
793
+ throw new Error(`Failed to validate EVM address for account ${activeAccountType}:${activeAccountId}: ${addressError.message}`);
794
+ }
795
+ }
796
+ return {
797
+ address,
798
+ decryptedPrivateKey,
799
+ };
800
+ }
801
+ catch (error) {
802
+ const vaultForLogging = this.getVault();
803
+ const isTestEnv = typeof process !== 'undefined' && process?.env?.NODE_ENV === 'test';
804
+ if (!isTestEnv) {
805
+ console.error('ERROR getDecryptedPrivateKey', {
806
+ error: error.message,
807
+ activeChain: this.getActiveChain(),
808
+ vault: {
809
+ activeAccountId: vaultForLogging?.activeAccount?.id,
810
+ activeAccountType: vaultForLogging?.activeAccount?.type,
811
+ },
812
+ });
813
+ }
814
+ this.validateAndHandleErrorByMessage(error.message);
815
+ throw error;
816
+ }
817
+ };
818
+ this.capturePsbtSigningContext = () => {
819
+ const session = this.sessionPassword;
820
+ const vault = this.getVault();
821
+ const selected = { ...vault.activeAccount };
822
+ const account = vault.accounts[selected.type]?.[selected.id];
823
+ const identity = { address: account?.address, xpub: account?.xpub };
824
+ const network = { ...vault.activeNetwork };
825
+ const assertCurrent = () => {
826
+ const current = this.getVault();
827
+ const currentAccount = current.accounts[selected.type]?.[selected.id];
828
+ if (!session ||
829
+ session.isCleared() ||
830
+ this.sessionPassword !== session ||
831
+ current.activeAccount.id !== selected.id ||
832
+ current.activeAccount.type !== selected.type ||
833
+ currentAccount?.address !== identity.address ||
834
+ currentAccount?.xpub !== identity.xpub ||
835
+ current.activeNetwork.kind !== network.kind ||
836
+ current.activeNetwork.chainId !== network.chainId ||
837
+ current.activeNetwork.slip44 !== network.slip44 ||
838
+ current.activeNetwork.url !== network.url) {
839
+ throw new Error('Wallet signing context changed');
840
+ }
841
+ };
842
+ assertCurrent();
843
+ return assertCurrent;
844
+ };
845
+ this.getSigner = () => {
846
+ if (!this.sessionPassword) {
847
+ throw new Error('Wallet is locked cant proceed with transaction');
848
+ }
849
+ if (this.getActiveChain() !== sysweb3_network_1.INetworkType.Syscoin) {
850
+ throw new Error('Switch to UTXO chain');
851
+ }
852
+ const vault = this.getVault();
853
+ const { activeAccount } = vault;
854
+ const accountId = activeAccount.id;
855
+ const accountType = activeAccount.type;
856
+ const assertCurrent = this.capturePsbtSigningContext();
857
+ // Determine signer type: HD or WIF single-address
858
+ let signerForUse;
859
+ if (accountType === types_1.KeyringAccountType.HDAccount) {
860
+ signerForUse = this.createOnDemandUTXOSigner(accountId);
861
+ }
862
+ else if (accountType === types_1.KeyringAccountType.Imported) {
863
+ // Decrypt stored key material
864
+ const decrypted = this.withSecureData((sessionPwd) => {
865
+ const account = vault.accounts[types_1.KeyringAccountType.Imported][accountId];
866
+ const res = crypto_js_1.default.AES.decrypt(account.xprv, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
867
+ if (!res)
868
+ throw new Error('Failed to decrypt imported account key');
869
+ return res;
870
+ });
871
+ if (this.isZprv(decrypted)) {
872
+ signerForUse = this.createFreshUTXOSigner(decrypted, accountId);
873
+ }
874
+ else {
875
+ // Treat as WIF single-address signer wrapper exposing sign(psbt)
876
+ const network = vault.activeNetwork;
877
+ const { networks } = (0, sysweb3_network_1.getNetworkConfig)(network.slip44, network.currency);
878
+ const isTestnet = network.slip44 === 1;
879
+ const bitcoinjsNetwork = isTestnet
880
+ ? networks.testnet
881
+ : networks.mainnet;
882
+ signerForUse = {
883
+ sign: async (psbt) => {
884
+ return await syscoinjs.utils.signWithWIF(psbt, decrypted, bitcoinjsNetwork);
885
+ },
886
+ };
887
+ }
888
+ }
889
+ else {
890
+ throw new Error(`Unsupported account type for UTXO signing: ${accountType}`);
891
+ }
892
+ const scope = {
893
+ account: vault.accounts[accountType][accountId],
894
+ accountId,
895
+ accountType,
896
+ network: vault.activeNetwork,
897
+ };
898
+ if (typeof signerForUse.getRootNode === 'function') {
899
+ const getRootNode = signerForUse.getRootNode.bind(signerForUse);
900
+ const guardPath = (0, psbt_account_scope_1.createPsbtDerivationGuard)(scope);
901
+ signerForUse.getRootNode = () => {
902
+ const root = getRootNode();
903
+ const scopedRoot = Object.create(root);
904
+ scopedRoot.derivePath = (path) => {
905
+ guardPath(path);
906
+ return root.derivePath(path);
907
+ };
908
+ return scopedRoot;
909
+ };
910
+ }
911
+ const sign = signerForUse.sign.bind(signerForUse);
912
+ signerForUse.sign = async (psbt) => {
913
+ assertCurrent();
914
+ (0, psbt_account_scope_1.assertPsbtAccountScope)(psbt, scope);
915
+ const result = await sign(psbt);
916
+ assertCurrent();
917
+ return result;
918
+ };
919
+ // Create syscoinjs instance with current network (no need to attach signer for signing flow)
920
+ const network = vault.activeNetwork;
921
+ const networkConfig = (0, sysweb3_network_1.getNetworkConfig)(network.slip44, network.currency);
922
+ const isTestnet = network.slip44 === 1;
923
+ const bitcoinjsNetwork = isTestnet
924
+ ? networkConfig?.networks?.testnet
925
+ : networkConfig?.networks?.mainnet;
926
+ const syscoinMainSigner = new syscoinjs.SyscoinJSLib(null, network.url, bitcoinjsNetwork);
927
+ return {
928
+ hd: signerForUse,
929
+ main: syscoinMainSigner,
930
+ };
931
+ };
932
+ // Read-only version that works when wallet is locked
933
+ this.getReadOnlySigner = () => {
934
+ if (this.getActiveChain() !== sysweb3_network_1.INetworkType.Syscoin) {
935
+ throw new Error('Switch to UTXO chain');
936
+ }
937
+ // Create syscoinjs instance without HD signer for read-only operations
938
+ const vault = this.getVault();
939
+ const network = vault.activeNetwork;
940
+ const networkConfig = (0, sysweb3_network_1.getNetworkConfig)(network.slip44, network.currency);
941
+ const isTestnet = network.slip44 === 1;
942
+ const bitcoinjsNetwork = isTestnet
943
+ ? networkConfig?.networks?.testnet
944
+ : networkConfig?.networks?.mainnet;
945
+ const syscoinMainSigner = new syscoinjs.SyscoinJSLib(null, // No HD signer needed for read-only operations
946
+ network.url, bitcoinjsNetwork);
947
+ return {
948
+ main: syscoinMainSigner,
949
+ };
950
+ };
951
+ this.getAccountsState = () => {
952
+ const vault = this.getVault();
953
+ const { accounts, activeAccount, activeNetwork } = vault;
954
+ return {
955
+ activeAccountId: activeAccount.id,
956
+ accounts,
957
+ activeAccountType: activeAccount.type,
958
+ activeNetwork,
959
+ };
960
+ };
961
+ /**
962
+ *
963
+ * @param password
964
+ * @param salt
965
+ * @returns derived key: hex string
966
+ */
967
+ this.encryptSHA512 = (password, salt) => {
968
+ // Session/encryption key derivation (used to encrypt/decrypt xprv in-memory and persisted state).
969
+ // PBKDF2 with SHA-512, 20,000 iterations (prod default), 256-bit output.
970
+ // NOTE: Tests override iterations to keep CI fast.
971
+ const isTestEnv = typeof process !== 'undefined' && process?.env?.NODE_ENV === 'test';
972
+ const iterations = Number.parseInt(process?.env?.SYSWEB3_PBKDF2_ENC_ITERS || '', 10) ||
973
+ (isTestEnv ? 1000 : 20000);
974
+ const key = crypto_js_1.default.PBKDF2(password, crypto_js_1.default.enc.Hex.parse(salt), {
975
+ keySize: 256 / 32, // 256 bits
976
+ iterations,
977
+ hasher: crypto_js_1.default.algo.SHA512,
978
+ });
979
+ return key.toString();
980
+ };
981
+ this.hasWebCrypto = () => {
982
+ // MV3 service worker & extension pages: globalThis.crypto.subtle exists.
983
+ // Jest tests mock global.crypto without subtle -> fallback to CryptoJS.
984
+ return !!globalThis?.crypto?.subtle;
985
+ };
986
+ this.hexToBytes = (hex) => {
987
+ const clean = (hex || '').trim();
988
+ if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length % 2 !== 0) {
989
+ throw new Error('Invalid hex string');
990
+ }
991
+ const out = new Uint8Array(clean.length / 2);
992
+ for (let i = 0; i < out.length; i++) {
993
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
994
+ }
995
+ return out;
996
+ };
997
+ this.bytesToHex = (bytes) => {
998
+ const u8 = new Uint8Array(bytes);
999
+ let hex = '';
1000
+ for (let i = 0; i < u8.length; i++) {
1001
+ hex += u8[i].toString(16).padStart(2, '0');
1002
+ }
1003
+ return hex;
1004
+ };
1005
+ this.getEncIterations = () => {
1006
+ const isTestEnv = typeof process !== 'undefined' && process?.env?.NODE_ENV === 'test';
1007
+ return (Number.parseInt(process?.env?.SYSWEB3_PBKDF2_ENC_ITERS || '', 10) ||
1008
+ (isTestEnv ? 1000 : 900000));
1009
+ };
1010
+ this.getSysActivePrivateKey = (hd) => {
1011
+ if (hd === null)
1012
+ throw new Error('No HD Signer');
1013
+ const accountIndex = hd.Signer.accountIndex;
1014
+ // Verify the account exists now
1015
+ if (!hd.Signer.accounts.has(accountIndex)) {
1016
+ throw new Error(`Account at index ${accountIndex} could not be created`);
1017
+ }
1018
+ return hd.Signer.accounts.get(accountIndex).getAccountPrivateKey();
1019
+ };
1020
+ this.getInitialAccountData = ({ label, signer, sysAccount, xprv, }) => {
1021
+ const { address, xpub } = sysAccount;
1022
+ return {
1023
+ id: signer.Signer.accountIndex,
1024
+ label: label || `Account ${signer.Signer.accountIndex + 1}`,
1025
+ xpub,
1026
+ xprv,
1027
+ address,
1028
+ isTrezorWallet: false,
1029
+ isLedgerWallet: false,
1030
+ isImported: false,
1031
+ };
1032
+ };
1033
+ this.getFormattedBackendAccount = async ({ signer, }) => {
1034
+ // MUCH SIMPLER: Just use the signer directly - no BIP84 needed!
1035
+ // Get address directly from the signer (always correct for current network)
1036
+ const address = signer.createAddress(0, false, 84);
1037
+ const xpub = signer.getAccountXpub();
1038
+ return {
1039
+ address,
1040
+ xpub,
1041
+ };
1042
+ };
1043
+ this.setLatestIndexesFromXPubTokens = function (tokens) {
1044
+ let changeIndexInternal = -1, receivingIndexInternal = -1;
1045
+ if (tokens) {
1046
+ tokens.forEach((token) => {
1047
+ if (!token.transfers || !token.path) {
1048
+ return {
1049
+ changeIndex: changeIndexInternal + 1,
1050
+ receivingIndex: receivingIndexInternal + 1,
1051
+ };
1052
+ }
1053
+ const transfers = parseInt(token.transfers, 10);
1054
+ if (token.path && transfers > 0) {
1055
+ const splitPath = token.path.split('/');
1056
+ if (splitPath.length >= 6) {
1057
+ const change = parseInt(splitPath[4], 10);
1058
+ const index = parseInt(splitPath[5], 10);
1059
+ if (change === 1) {
1060
+ if (index > changeIndexInternal) {
1061
+ changeIndexInternal = index;
1062
+ }
1063
+ }
1064
+ else if (index > receivingIndexInternal) {
1065
+ receivingIndexInternal = index;
1066
+ }
1067
+ }
1068
+ }
1069
+ });
1070
+ }
1071
+ return {
1072
+ changeIndex: changeIndexInternal + 1,
1073
+ receivingIndex: receivingIndexInternal + 1,
1074
+ };
1075
+ };
1076
+ this.getBasicWeb3AccountInfo = (id, label) => {
1077
+ return {
1078
+ id,
1079
+ isTrezorWallet: false,
1080
+ isLedgerWallet: false,
1081
+ label: label ? label : `Account ${id + 1}`,
1082
+ };
1083
+ };
1084
+ this.setDerivedWeb3Accounts = async (id, label) => {
1085
+ try {
1086
+ // For account creation, derive from mnemonic (since account doesn't exist yet)
1087
+ const mnemonic = this.getDecryptedMnemonic();
1088
+ const derivationPath = (0, derivation_paths_1.getAddressDerivationPath)('eth', 60, 0, false, id);
1089
+ const derivedAccount = (0, evm_local_signer_1.deriveEvmAccountFromMnemonic)(mnemonic, derivationPath);
1090
+ const basicAccountInfo = this.getBasicWeb3AccountInfo(id, label);
1091
+ const createdAccount = {
1092
+ address: derivedAccount.address,
1093
+ xpub: derivedAccount.publicKey,
1094
+ xprv: this.withSecureData((sessionPwd) => {
1095
+ return crypto_js_1.default.AES.encrypt(derivedAccount.privateKey, sessionPwd).toString();
1096
+ }),
1097
+ isImported: false,
1098
+ ...basicAccountInfo,
1099
+ balances: { syscoin: 0, ethereum: 0 },
1100
+ };
1101
+ // NOTE: Account creation should be dispatched to Redux store, not stored here
1102
+ // Return the account data for Pali to add to store
1103
+ return createdAccount;
1104
+ }
1105
+ catch (error) {
1106
+ console.log('ERROR setDerivedWeb3Accounts', {
1107
+ error,
1108
+ });
1109
+ this.validateAndHandleErrorByMessage(error.message);
1110
+ throw error;
1111
+ }
1112
+ };
1113
+ this.setSignerEVM = async (network) => {
1114
+ const abortController = new AbortController();
1115
+ try {
1116
+ // With multi-keyring architecture, this is only called on EVM keyrings
1117
+ this.ethereumTransaction.setWeb3Provider(network);
1118
+ abortController.abort();
1119
+ }
1120
+ catch (error) {
1121
+ abortController.abort();
1122
+ throw new Error(`SetSignerEVM: Failed with ${error}`);
1123
+ }
1124
+ };
1125
+ this.clearTemporaryLocalKeys = async () => {
1126
+ // Clear the vault completely.
1127
+ // For v4, the vault is encrypted with a derived key, so the safest wipe is to delete the stored blob.
1128
+ await this.storage.deleteItem('vault');
1129
+ // Remove vault-keys from storage so no vault exists at all
1130
+ await this.storage.deleteItem('vault-keys');
1131
+ console.log('[KeyringManager] Temporary local keys cleared');
1132
+ this.logout();
1133
+ };
1134
+ // NEW: Separate session initialization from account creation
1135
+ this.initializeSession = async (seedPhrase, password) => {
1136
+ // Validate inputs first
1137
+ if (!BIP84.validateMnemonic(seedPhrase)) {
1138
+ throw new Error('Invalid Seed');
1139
+ }
1140
+ const [vault, vaultKeys] = await Promise.all([
1141
+ this.storage.get('vault'),
1142
+ this.storage.get('vault-keys'),
1143
+ ]);
1144
+ const hasVault = vault !== undefined && vault !== null;
1145
+ const hasVaultKeys = vaultKeys !== undefined && vaultKeys !== null;
1146
+ const livePassword = this.sessionPassword;
1147
+ const liveMnemonic = this.sessionMnemonic;
1148
+ // Only an already-unlocked, matching session may repeat initialization.
1149
+ // Restoring any existing wallet must use unlock(), never rewrite its vault.
1150
+ if (livePassword &&
1151
+ liveMnemonic &&
1152
+ !livePassword.isCleared() &&
1153
+ !liveMnemonic.isCleared()) {
1154
+ if (!hasVault || !hasVaultKeys || !vaultKeys.salt) {
1155
+ throw new Error('Cannot initialize a new vault over existing wallet storage');
1156
+ }
1157
+ const sessionPasswordSaltedHash = await this.deriveStoredSessionKey(password, vaultKeys);
1158
+ if (livePassword === this.sessionPassword &&
1159
+ liveMnemonic === this.sessionMnemonic &&
1160
+ sessionPasswordSaltedHash === this.getSessionPasswordString()) {
1161
+ // Same password - check if it's the same mnemonic to ensure full idempotency
1162
+ let currentMnemonic;
1163
+ try {
1164
+ currentMnemonic = this.withSecureData((sessionPwd, sessionMnemonic) => {
1165
+ return crypto_js_1.default.AES.decrypt(sessionMnemonic, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
1166
+ });
1167
+ }
1168
+ catch (error) {
1169
+ // If we can't decrypt, fall through to error
1170
+ }
1171
+ if (currentMnemonic === seedPhrase) {
1172
+ const storedVault = await this.vaultPersistence.getDecryptedVault(sessionPasswordSaltedHash);
1173
+ if (livePassword === this.sessionPassword &&
1174
+ liveMnemonic === this.sessionMnemonic &&
1175
+ !livePassword.isCleared() &&
1176
+ !liveMnemonic.isCleared() &&
1177
+ storedVault?.mnemonic === seedPhrase) {
1178
+ // This is a read-only identity check, not a second vault write.
1179
+ return;
1180
+ }
1181
+ }
1182
+ }
1183
+ // Different password or mnemonic - this is not a simple re-initialization
1184
+ throw new Error('Wallet already initialized with different parameters. Unlock the existing wallet or explicitly remove it before starting setup.');
1185
+ }
1186
+ if (hasVault || hasVaultKeys) {
1187
+ throw new Error('Cannot initialize a new vault over existing wallet storage');
1188
+ }
1189
+ const salt = crypto_1.default.randomBytes(16).toString('hex');
1190
+ // v4 stores only the salt on disk. A genuinely fresh initialization always
1191
+ // commits its own salt and ciphertext together under the vault mutex.
1192
+ const sessionPasswordSaltedHash = await this.deriveStoredSessionKey(password, { salt });
1193
+ // Encrypt and store vault (mnemonic storage) - now uses single vault for all networks
1194
+ await this.vaultPersistence.setEncryptedVault({
1195
+ mnemonic: seedPhrase, // Store plain mnemonic - setEncryptedVault will encrypt the entire vault
1196
+ },
1197
+ // v4 vault is encrypted with the derived session password key (PBKDF2 output)
1198
+ sessionPasswordSaltedHash, { salt });
1199
+ await this.recreateSessionFromVault(sessionPasswordSaltedHash);
1200
+ };
1201
+ // NEW: Create first account without signer setup
1202
+ this.createFirstAccount = async (label) => {
1203
+ if (!this.sessionPassword || !this.sessionMnemonic) {
1204
+ throw new Error('Session must be initialized first. Call initializeSession.');
1205
+ }
1206
+ const vault = this.getVault();
1207
+ const network = vault.activeNetwork;
1208
+ if (network.kind === sysweb3_network_1.INetworkType.Syscoin) {
1209
+ // UTXO accounts get network-aware labels since each network has separate keyrings
1210
+ const defaultLabel = label || this.generateNetworkAwareLabel(0, network);
1211
+ // Create UTXO account using on-demand signer
1212
+ const freshHDSigner = this.createOnDemandUTXOSigner(0);
1213
+ const sysAccount = await this.getFormattedBackendAccount({
1214
+ signer: freshHDSigner,
1215
+ });
1216
+ const encryptedXprv = this.getEncryptedXprv(freshHDSigner);
1217
+ return {
1218
+ ...this.getInitialAccountData({
1219
+ label: defaultLabel,
1220
+ signer: freshHDSigner,
1221
+ sysAccount,
1222
+ xprv: encryptedXprv,
1223
+ }),
1224
+ balances: { syscoin: 0, ethereum: 0 },
1225
+ };
1226
+ }
1227
+ else {
1228
+ // EVM accounts get generic labels since they work across all EVM networks
1229
+ const defaultLabel = label || 'Account 1';
1230
+ return await this.setDerivedWeb3Accounts(0, defaultLabel);
1231
+ }
1232
+ };
1233
+ this.initializeWalletSecurely = async (seedPhrase, password) => {
1234
+ // Use new separated approach
1235
+ await this.initializeSession(seedPhrase, password);
1236
+ return await this.createFirstAccount();
1237
+ };
1238
+ if (!dependencies ||
1239
+ typeof dependencies.authority !== 'object' ||
1240
+ dependencies.authority === null) {
1241
+ throw new TypeError('Keyring core requires an explicit wallet authority');
1242
+ }
1243
+ if (typeof dependencies.vaultPersistence?.getDecryptedVault !== 'function' ||
1244
+ typeof dependencies.vaultPersistence?.setEncryptedVault !== 'function') {
1245
+ throw new TypeError('Keyring core requires bound vault persistence');
1246
+ }
1247
+ this.authority = dependencies.authority;
1248
+ this.storage = dependencies.storage;
1249
+ this.vaultPersistence = dependencies.vaultPersistence;
1250
+ this.ledgerSigner = dependencies.ledgerSigner;
1251
+ this.trezorSigner = dependencies.trezorSigner;
1252
+ this.syscoinHardwareSigners = { ...dependencies.syscoinHardwareSigners };
1253
+ this.writeUtf8Diagnostic(false);
1254
+ this.utf8Error = false;
1255
+ this.initialTrezorAccountState = initial_state_1.initialActiveTrezorAccountState;
1256
+ this.initialLedgerAccountState = initial_state_1.initialActiveLedgerAccountState;
1257
+ this.syscoinTransaction = this.createSyscoinTransactions();
1258
+ this.ethereumTransaction = new ethereum_1.EthereumTransactions(this.getNetwork, this.getDecryptedPrivateKey, this.getAccountsState, this.ledgerSigner, this.trezorSigner, this.capturePsbtSigningContext);
1259
+ }
1260
+ // Convenience method for complete setup after construction
1261
+ async initialize(seed, password, network) {
1262
+ // Set the network if provided (this is crucial for proper address derivation)
1263
+ if (network) {
1264
+ await this.setSignerNetwork(network);
1265
+ }
1266
+ // Use the new secure initialization method (eliminates temporary plaintext storage)
1267
+ const account = await this.initializeWalletSecurely(seed, password);
1268
+ // NOTE: Active account management is now handled by vault state/Redux
1269
+ // No need to explicitly set active account - it's managed externally
1270
+ return account;
1271
+ }
1272
+ /**
1273
+ * Returns canLogin:false only when the first vault authentication fails.
1274
+ * Storage, platform and session restoration failures reject so callers do
1275
+ * not charge a failed password attempt for an operational error.
1276
+ */
1277
+ async unlock(password) {
1278
+ let authenticated = false;
1279
+ try {
1280
+ const vaultKeys = await this.storage.get('vault-keys');
1281
+ if (!vaultKeys) {
1282
+ throw new Error('Vault keys not found. Reload the wallet and try again.');
1283
+ }
1284
+ // v4: Validate password by deriving the session key once and decrypting the vault with it.
1285
+ // This avoids an extra KDF pass just for a stored verifier.
1286
+ const { salt } = vaultKeys;
1287
+ // Derive session encryption key (in-memory only) used to encrypt/decrypt xprv fields
1288
+ // IMPORTANT: This MUST NOT be the same value as the stored verifier above.
1289
+ let sessionPasswordKey = await this.deriveStoredSessionKey(password, vaultKeys);
1290
+ // Handle migration from old vault format with currentSessionSalt
1291
+ if (vaultKeys.currentSessionSalt) {
1292
+ console.log('[KeyringManager] Detected old vault format, handling session migration...');
1293
+ // The old format used currentSessionSalt for session data encryption
1294
+ // We need to use it temporarily to decrypt the mnemonic correctly
1295
+ const oldSessionPassword = this.encryptSHA512(password, vaultKeys.currentSessionSalt);
1296
+ // v3 CBC vaults use the raw password; migrated GCM vaults use the
1297
+ // derived key. Selecting by stored format also permits a safe retry
1298
+ // if the vault write succeeded but the metadata write was interrupted.
1299
+ const { mnemonic } = await this.vaultPersistence.getDecryptedVault(sessionPasswordKey, password);
1300
+ authenticated = true;
1301
+ const isValidSecret = (value) => {
1302
+ if (typeof value !== 'string' || !value)
1303
+ return false;
1304
+ if (this.isSeedValid(value))
1305
+ return true;
1306
+ // Imported extended private keys can also be stored as the secret.
1307
+ if (!/^(xprv|yprv|zprv|tprv|uprv|vprv)/.test(value))
1308
+ return false;
1309
+ try {
1310
+ const decoded = bs58check_1.default.decode(value);
1311
+ return (decoded.length === 78 &&
1312
+ decoded[45] === 0 &&
1313
+ secp256k1_1.default.isPrivate(decoded.subarray(46)));
1314
+ }
1315
+ catch {
1316
+ return false;
1317
+ }
1318
+ };
1319
+ let decryptedMnemonic = mnemonic;
1320
+ if (!isValidSecret(decryptedMnemonic) && typeof mnemonic === 'string') {
1321
+ for (const legacyKey of [password, oldSessionPassword]) {
1322
+ try {
1323
+ const candidate = crypto_js_1.default.AES.decrypt(mnemonic, legacyKey).toString(crypto_js_1.default.enc.Utf8);
1324
+ if (isValidSecret(candidate)) {
1325
+ decryptedMnemonic = candidate;
1326
+ break;
1327
+ }
1328
+ }
1329
+ catch (error) {
1330
+ if (error?.message !== 'Malformed UTF-8 data')
1331
+ throw error;
1332
+ }
1333
+ }
1334
+ }
1335
+ if (!isValidSecret(decryptedMnemonic)) {
1336
+ throw new Error('Legacy vault secret could not be recovered. Existing vault preserved.');
1337
+ }
1338
+ // Do not change either stored record until a valid secret is recovered.
1339
+ await this.vaultPersistence.setEncryptedVault({ mnemonic: decryptedMnemonic }, sessionPasswordKey);
1340
+ console.log('[KeyringManager] Vault mnemonic format normalized');
1341
+ // Remove currentSessionSalt from vault-keys (v4 keeps only the salt on disk)
1342
+ const migratedVaultKeys = {
1343
+ salt: vaultKeys.salt,
1344
+ };
1345
+ await this.storage.set('vault-keys', migratedVaultKeys);
1346
+ console.log('[KeyringManager] Old vault format migration completed');
1347
+ }
1348
+ // v4 vault is encrypted with the derived session password key (PBKDF2 output).
1349
+ // If the password is wrong, this will throw and we return canLogin:false below.
1350
+ let decryptedVault;
1351
+ let legacyProfile = vaultKeys.keyDerivation === LEGACY_ENCRYPTION_KDF;
1352
+ try {
1353
+ decryptedVault = await this.vaultPersistence.getDecryptedVault(sessionPasswordKey);
1354
+ }
1355
+ catch (error) {
1356
+ // Only the historical CBC fallback used the 20k key without metadata.
1357
+ // Never try it for GCM, malformed records, or platform/storage failures.
1358
+ const rawVault = error instanceof storage_core_1.VaultAuthenticationError &&
1359
+ !vaultKeys.keyDerivation &&
1360
+ !vaultKeys.currentSessionSalt
1361
+ ? await this.storage.get('vault')
1362
+ : undefined;
1363
+ if (typeof rawVault !== 'string' || rawVault.trim().startsWith('{')) {
1364
+ throw error;
1365
+ }
1366
+ const legacyKey = await this.deriveLegacySessionKey(password, salt);
1367
+ decryptedVault = await this.vaultPersistence.getDecryptedVault(legacyKey);
1368
+ authenticated = true;
1369
+ sessionPasswordKey = legacyKey;
1370
+ // Keep the historical account wrapping key. Persist its profile before
1371
+ // GCM rewrapping so either interrupted write remains recoverable.
1372
+ await this.storage.set('vault-keys', {
1373
+ ...vaultKeys,
1374
+ keyDerivation: LEGACY_ENCRYPTION_KDF,
1375
+ });
1376
+ legacyProfile = true;
1377
+ }
1378
+ authenticated = true;
1379
+ if (legacyProfile && this.hasWebCrypto()) {
1380
+ const storedVault = await this.storage.get('vault');
1381
+ if (typeof storedVault === 'string' &&
1382
+ !storedVault.trim().startsWith('{')) {
1383
+ // A failed earlier rewrap can leave the authenticated profile plus
1384
+ // CBC. Retry that write without changing the account wrapping key.
1385
+ await this.vaultPersistence.setEncryptedVault(decryptedVault, sessionPasswordKey);
1386
+ }
1387
+ }
1388
+ // If session data missing or corrupted, recreate from vault
1389
+ if (!this.sessionMnemonic) {
1390
+ await this.recreateSessionFromVault(sessionPasswordKey);
1391
+ }
1392
+ // Re-initialize syscoin transaction handler if it was cleared on lock.
1393
+ // `lockWallet()` intentionally replaces it with a plain object to drop signer references,
1394
+ // so we must restore the real class instance on unlock.
1395
+ if (!this.syscoinTransaction ||
1396
+ typeof this.syscoinTransaction.getRecommendedFee !== 'function') {
1397
+ this.syscoinTransaction = this.createSyscoinTransactions();
1398
+ }
1399
+ // NOTE: Active account management is now handled by vault state/Redux
1400
+ // No need to explicitly set active account after unlock - it's managed externally
1401
+ const vault = this.getVault();
1402
+ if (vault.activeAccount?.id !== undefined && vault.activeAccount?.type) {
1403
+ // Check if the active account actually exists in the accounts map
1404
+ const accountType = vault.activeAccount.type;
1405
+ const accountId = vault.activeAccount.id;
1406
+ const accountExists = vault.accounts?.[accountType]?.[accountId];
1407
+ if (!accountExists) {
1408
+ console.log(`[KeyringManager] Active account ${accountType}:${accountId} not found in accounts map. This may indicate a migration from old vault format.`);
1409
+ // Signal that accounts need to be created after migration
1410
+ return {
1411
+ canLogin: true,
1412
+ needsAccountCreation: true,
1413
+ };
1414
+ }
1415
+ console.log(`[KeyringManager] Active account ${vault.activeAccount.id} available after unlock`);
1416
+ }
1417
+ return {
1418
+ canLogin: true,
1419
+ };
1420
+ }
1421
+ catch (error) {
1422
+ if (!authenticated && error instanceof storage_core_1.VaultAuthenticationError) {
1423
+ return { canLogin: false };
1424
+ }
1425
+ if (authenticated) {
1426
+ // lockWallet clears secret buffers synchronously; hardware cleanup
1427
+ // is best effort and must not hide the original operational error.
1428
+ void this.lockWallet().catch(() => undefined);
1429
+ }
1430
+ throw error;
1431
+ }
1432
+ }
1433
+ isWatchOnlyAccount(a) {
1434
+ if (a.isLedgerWallet || a.isTrezorWallet)
1435
+ return false;
1436
+ if (!a.xprv || a.xprv === '') {
1437
+ if (a.xpub === a.address)
1438
+ return true; // single-address imported
1439
+ if (this.isXpubLike(a.xpub) || this.isDescriptor(a.xpub))
1440
+ return true; // xpub/descriptor watch-only
1441
+ }
1442
+ return false;
1443
+ }
1444
+ privateRecordSession() {
1445
+ const password = this.sessionPassword;
1446
+ const mnemonic = this.sessionMnemonic;
1447
+ const revision = this.privateRecordSessionRevision;
1448
+ const assertCurrent = () => {
1449
+ if (!password ||
1450
+ !mnemonic ||
1451
+ password.isCleared() ||
1452
+ mnemonic.isCleared() ||
1453
+ this.sessionPassword !== password ||
1454
+ this.sessionMnemonic !== mnemonic ||
1455
+ this.privateRecordSessionRevision !== revision) {
1456
+ throw new Error('Private record session changed');
1457
+ }
1458
+ };
1459
+ assertCurrent();
1460
+ const root = this.getDecryptedMnemonic().normalize('NFKD');
1461
+ if (!root || root.length > 4096)
1462
+ throw new Error('Invalid private record root');
1463
+ return { secret: new TextEncoder().encode(root), assertCurrent };
1464
+ }
1465
+ /** Stable local profile identifier; never an account address or a key. */
1466
+ async getPrivateRecordProfileId() {
1467
+ const session = this.privateRecordSession();
1468
+ try {
1469
+ const profile = await (0, private_records_1.privateRecordProfileId)(session.secret, session.assertCurrent);
1470
+ session.assertCurrent();
1471
+ return profile;
1472
+ }
1473
+ finally {
1474
+ session.secret.fill(0);
1475
+ }
1476
+ }
1477
+ /** Encrypt caller-owned bytes; persistence and encrypted backup belong to the caller. */
1478
+ async encryptPrivateRecord(params) {
1479
+ const session = this.privateRecordSession();
1480
+ try {
1481
+ const envelope = await (0, private_records_1.encryptPrivateRecordBytes)(session.secret, params, session.assertCurrent);
1482
+ session.assertCurrent();
1483
+ return envelope;
1484
+ }
1485
+ finally {
1486
+ session.secret.fill(0);
1487
+ }
1488
+ }
1489
+ async decryptPrivateRecord(params) {
1490
+ const session = this.privateRecordSession();
1491
+ let plaintext;
1492
+ try {
1493
+ plaintext = await (0, private_records_1.decryptPrivateRecordBytes)(session.secret, params, session.assertCurrent);
1494
+ session.assertCurrent();
1495
+ return plaintext;
1496
+ }
1497
+ catch (error) {
1498
+ plaintext?.fill(0);
1499
+ throw error;
1500
+ }
1501
+ finally {
1502
+ session.secret.fill(0);
1503
+ }
1504
+ }
1505
+ async importTrezorAccount(label) {
1506
+ const vault = this.getVault();
1507
+ const currency = vault.activeNetwork.currency;
1508
+ if (!currency) {
1509
+ throw new Error('Active network currency is not defined');
1510
+ }
1511
+ // Use getNextAccountId to filter out placeholder accounts
1512
+ const nextIndex = this.getNextAccountId(vault.accounts[types_1.KeyringAccountType.Trezor]);
1513
+ const importedAccount = await this._createTrezorAccount(currency, vault.activeNetwork.slip44, nextIndex);
1514
+ importedAccount.label = label ? label : `Trezor ${importedAccount.id + 1}`;
1515
+ // NOTE: Account creation should be dispatched to Redux store, not updated here
1516
+ // The calling code should handle the Redux dispatch
1517
+ // Return the created account for Pali to add to store
1518
+ return importedAccount;
1519
+ }
1520
+ async importLedgerAccount(label) {
1521
+ try {
1522
+ const vault = this.getVault();
1523
+ const currency = vault.activeNetwork.currency;
1524
+ if (!currency) {
1525
+ throw new Error('Active network currency is not defined');
1526
+ }
1527
+ // Use getNextAccountId to filter out placeholder accounts
1528
+ const nextIndex = this.getNextAccountId(vault.accounts[types_1.KeyringAccountType.Ledger]);
1529
+ const importedAccount = await this._createLedgerAccount(currency, vault.activeNetwork.slip44, nextIndex);
1530
+ importedAccount.label = label
1531
+ ? label
1532
+ : `Ledger ${importedAccount.id + 1}`;
1533
+ // NOTE: Account creation should be dispatched to Redux store, not updated here
1534
+ // The calling code should handle the Redux dispatch
1535
+ // Return the created account for Pali to add to store
1536
+ return importedAccount;
1537
+ }
1538
+ catch (error) {
1539
+ console.log({ error });
1540
+ throw error;
1541
+ }
1542
+ }
1543
+ async importAccount(privKey, label, options) {
1544
+ // Check if wallet is unlocked
1545
+ if (!this.isUnlocked()) {
1546
+ throw new Error('Wallet must be unlocked to import accounts');
1547
+ }
1548
+ const importedAccount = await this._getPrivateKeyAccountInfos(privKey, label, options);
1549
+ // NOTE: Account creation should be dispatched to Redux store, not updated here
1550
+ // The calling code should handle the Redux dispatch
1551
+ // Return the created account for Pali to add to store
1552
+ return importedAccount;
1553
+ }
1554
+ // Import a WIF on UTXO networks and force legacy P2PKH address/type.
1555
+ // Keeps it as a single-address Imported account, storing the address in both xpub and address.
1556
+ async importWatchOnly(identifier, label) {
1557
+ // Validate via Blockbook and create a watch-only Imported account
1558
+ const vault = this.getVault();
1559
+ const { accounts, activeNetwork } = vault;
1560
+ if (!identifier || typeof identifier !== 'string') {
1561
+ throw new Error('Identifier is required');
1562
+ }
1563
+ const isXpub = this.isXpubLike(identifier);
1564
+ const isDesc = this.isDescriptor(identifier);
1565
+ const isAddress = !isXpub && !isDesc;
1566
+ // Compute address field
1567
+ let addressToStore = identifier;
1568
+ if (isDesc) {
1569
+ // Keep the descriptor as the history reference, never as a recipient.
1570
+ // Backend-provided address metadata must not select the deposit address.
1571
+ addressToStore = (0, watch_descriptor_1.deriveDescriptorAddress)(identifier, activeNetwork);
1572
+ }
1573
+ else if (isXpub) {
1574
+ // Minimal approach: treat any extended pubkey as BIP84 by converting to zpub/vpub
1575
+ const { types } = (0, sysweb3_network_1.getNetworkConfig)(activeNetwork.slip44, activeNetwork.currency || 'Syscoin');
1576
+ const target = activeNetwork.slip44 === 1
1577
+ ? types.zPubType.testnet.vpub
1578
+ : types.zPubType.mainnet.zpub;
1579
+ const bip84Key = (0, derivation_paths_1.convertExtendedKeyVersion)(identifier, target);
1580
+ addressToStore = await this.getAddress(bip84Key, false, {
1581
+ forceIndex0: true,
1582
+ });
1583
+ }
1584
+ // Validate duplicates across all account buckets, including passkey smart accounts.
1585
+ if (this.accountAddressExists(accounts, addressToStore) ||
1586
+ ((isXpub || isDesc) &&
1587
+ Object.values(accounts || {}).some((bucket) => Object.values(bucket || {}).some((account) => account?.xpub === identifier)))) {
1588
+ throw new Error('Account already exists on your Wallet.');
1589
+ }
1590
+ // Confirm with Blockbook
1591
+ const options = 'details=basic';
1592
+ // Validate against Blockbook directly to capture precise error details (e.g., checksum mismatch)
1593
+ const baseUrl = activeNetwork.url.replace(/\/$/, '');
1594
+ const path = isXpub || isDesc ? '/api/v2/xpub/' : '/api/v2/address/';
1595
+ const url = `${baseUrl}${path}${encodeURIComponent(identifier)}?${options}`;
1596
+ let res = null;
1597
+ try {
1598
+ const response = await fetch(url);
1599
+ if (!response.ok) {
1600
+ let errorText = response.statusText || 'Request failed';
1601
+ try {
1602
+ const bodyText = await response.text();
1603
+ if (bodyText) {
1604
+ try {
1605
+ const json = JSON.parse(bodyText);
1606
+ if (json && json.error) {
1607
+ errorText = json.error;
1608
+ }
1609
+ else {
1610
+ errorText = bodyText;
1611
+ }
1612
+ }
1613
+ catch {
1614
+ errorText = bodyText;
1615
+ }
1616
+ }
1617
+ }
1618
+ catch (parseError) {
1619
+ // ignore body parse error; fall back to statusText
1620
+ }
1621
+ throw new Error(errorText);
1622
+ }
1623
+ res = await response.json();
1624
+ }
1625
+ catch (e) {
1626
+ throw new Error(e?.message || 'Identifier validation failed');
1627
+ }
1628
+ if (!res) {
1629
+ throw new Error('Identifier not found on the active network');
1630
+ }
1631
+ const id = this.getNextAccountId(accounts[types_1.KeyringAccountType.Imported]);
1632
+ const defaultLabel = label || `Watch-only ${id + 1}`;
1633
+ const balances = { syscoin: 0, ethereum: 0 };
1634
+ const watchOnlyAccount = {
1635
+ ...initial_state_1.initialActiveImportedAccountState,
1636
+ address: addressToStore,
1637
+ label: defaultLabel,
1638
+ id,
1639
+ balances,
1640
+ isImported: true,
1641
+ xprv: '',
1642
+ xpub: isAddress ? addressToStore : identifier,
1643
+ assets: {
1644
+ syscoin: [],
1645
+ ethereum: [],
1646
+ },
1647
+ };
1648
+ return watchOnlyAccount;
1649
+ }
1650
+ validateZprv(zprv, targetNetwork) {
1651
+ // Use the active network if targetNetwork is not provided
1652
+ const networkToValidateAgainst = targetNetwork || this.getVault().activeNetwork;
1653
+ if (!networkToValidateAgainst) {
1654
+ throw new Error('No network available for validation');
1655
+ }
1656
+ try {
1657
+ // Check if it looks like an extended key based on known prefixes
1658
+ const knownExtendedKeyPrefixes = [
1659
+ 'xprv',
1660
+ 'xpub',
1661
+ 'yprv',
1662
+ 'ypub',
1663
+ 'zprv',
1664
+ 'zpub',
1665
+ 'tprv',
1666
+ 'tpub',
1667
+ 'uprv',
1668
+ 'upub',
1669
+ 'vprv',
1670
+ 'vpub',
1671
+ ];
1672
+ const prefix = zprv.substring(0, 4);
1673
+ const looksLikeExtendedKey = knownExtendedKeyPrefixes.includes(prefix);
1674
+ // Only check prefix validity if it looks like an extended key
1675
+ if (looksLikeExtendedKey) {
1676
+ const validBip84Prefixes = ['zprv', 'vprv']; // zprv for mainnet, vprv for testnet
1677
+ if (!validBip84Prefixes.includes(prefix)) {
1678
+ throw new Error(`Invalid key prefix '${prefix}'. Only BIP84 keys (zprv/vprv) are supported for UTXO imports. BIP44 keys (xprv/tprv) are not supported.`);
1679
+ }
1680
+ }
1681
+ else {
1682
+ // Not an extended key format
1683
+ throw new Error('Not an extended private key');
1684
+ }
1685
+ const bip32 = (0, bip32_1.BIP32Factory)(secp256k1_1.default);
1686
+ const decoded = bs58check_1.default.decode(zprv);
1687
+ if (decoded.length !== 78) {
1688
+ throw new Error('Invalid length for a BIP-32 key');
1689
+ }
1690
+ // Get network configuration for the target network
1691
+ const { networks, types } = (0, sysweb3_network_1.getNetworkConfig)(networkToValidateAgainst.slip44, networkToValidateAgainst.currency || 'Bitcoin');
1692
+ // For BIP84 (zprv/zpub), we need to use the correct magic bytes from zPubType
1693
+ // Determine key type: zprv = mainnet key, vprv = testnet key
1694
+ const keyIsTestnet = prefix === 'vprv';
1695
+ // Determine target network type: testnet networks typically have slip44 1
1696
+ const targetIsTestnet = networkToValidateAgainst.slip44 === 1;
1697
+ // Cross-network validation: reject if key type doesn't match target network
1698
+ if (keyIsTestnet && !targetIsTestnet) {
1699
+ throw new Error(`Extended private key is not compatible with ${networkToValidateAgainst.label}. ` +
1700
+ `This appears to be a testnet key (${prefix}) but the target network is mainnet.`);
1701
+ }
1702
+ if (!keyIsTestnet && targetIsTestnet) {
1703
+ throw new Error(`Extended private key is not compatible with ${networkToValidateAgainst.label}. ` +
1704
+ `This appears to be a mainnet key (${prefix}) but the target network is testnet.`);
1705
+ }
1706
+ const pubTypes = keyIsTestnet
1707
+ ? types.zPubType.testnet
1708
+ : types.zPubType.mainnet;
1709
+ const baseNetwork = keyIsTestnet ? networks.testnet : networks.mainnet;
1710
+ const network = {
1711
+ ...baseNetwork,
1712
+ bip32: {
1713
+ public: parseInt(pubTypes.vpub || pubTypes.zpub, 16),
1714
+ private: parseInt(pubTypes.vprv || pubTypes.zprv, 16),
1715
+ },
1716
+ };
1717
+ // Validate that the key prefix matches the expected network format
1718
+ // This ensures the key was generated for a compatible network
1719
+ const expectedPrefixes = ['zprv', 'vprv', 'xprv', 'yprv']; // Accept various BIP32/84 formats
1720
+ if (!expectedPrefixes.includes(prefix)) {
1721
+ throw new Error(`Invalid extended private key prefix: ${prefix}. Expected one of: ${expectedPrefixes.join(', ')}`);
1722
+ }
1723
+ // Strict network matching - only allow keys that match the target network
1724
+ let node;
1725
+ try {
1726
+ node = bip32.fromBase58(zprv, network);
1727
+ }
1728
+ catch (e) {
1729
+ throw new Error(`Extended private key is not compatible with ${networkToValidateAgainst.label}. Please use a key generated for this specific network.`);
1730
+ }
1731
+ if (!node.privateKey) {
1732
+ throw new Error('Private key not found in extended private key');
1733
+ }
1734
+ if (!secp256k1_1.default.isPrivate(node.privateKey)) {
1735
+ throw new Error('Invalid private key for secp256k1 curve');
1736
+ }
1737
+ return {
1738
+ isValid: true,
1739
+ node,
1740
+ network,
1741
+ message: 'The extended private key is valid for this network.',
1742
+ };
1743
+ }
1744
+ catch (error) {
1745
+ return { isValid: false, message: error.message };
1746
+ }
1747
+ }
1748
+ validateWif(wif, targetNetwork) {
1749
+ // Use the active network if targetNetwork is not provided
1750
+ const networkToValidateAgainst = targetNetwork || this.getVault().activeNetwork;
1751
+ if (!networkToValidateAgainst) {
1752
+ throw new Error('No network available for validation');
1753
+ }
1754
+ try {
1755
+ // Get bitcoinjs network for the target network (Syscoin/BTC etc.)
1756
+ const { networks } = (0, sysweb3_network_1.getNetworkConfig)(networkToValidateAgainst.slip44, networkToValidateAgainst.currency || 'Bitcoin');
1757
+ const isTestnet = networkToValidateAgainst.slip44 === 1;
1758
+ const bitcoinNetwork = isTestnet ? networks.testnet : networks.mainnet;
1759
+ // Try to parse the WIF for the given network
1760
+ const keyPair = syscoinjs.utils.bitcoinjs.ECPair.fromWIF(wif, bitcoinNetwork);
1761
+ if (!keyPair || !keyPair.privateKey)
1762
+ throw new Error('Invalid WIF private key');
1763
+ // Derive an address based on network capability
1764
+ // Try different address types to ensure the key can derive addresses
1765
+ let address;
1766
+ try {
1767
+ // Try P2TR (Taproot) first if bech32 is supported
1768
+ if (bitcoinNetwork.bech32) {
1769
+ try {
1770
+ address = bjs.payments.p2wpkh({
1771
+ pubkey: keyPair.publicKey,
1772
+ network: bitcoinNetwork,
1773
+ }).address;
1774
+ }
1775
+ catch (e) {
1776
+ // P2TR might not be supported, try P2WPKH
1777
+ }
1778
+ }
1779
+ if (!address) {
1780
+ address = bjs.payments.p2pkh({
1781
+ pubkey: keyPair.publicKey,
1782
+ network: bitcoinNetwork,
1783
+ }).address;
1784
+ }
1785
+ }
1786
+ catch (e) {
1787
+ // ignore and handle below
1788
+ }
1789
+ if (!address)
1790
+ throw new Error('Failed to derive address from WIF');
1791
+ return { isValid: true };
1792
+ }
1793
+ catch (error) {
1794
+ return { isValid: false, message: error.message };
1795
+ }
1796
+ }
1797
+ writeUtf8Diagnostic(hasUtf8Error) {
1798
+ try {
1799
+ void Promise.resolve(this.storage.set('utf8Error', { hasUtf8Error })).catch(() => undefined);
1800
+ }
1801
+ catch {
1802
+ // This diagnostic must not interrupt authentication or become an
1803
+ // unhandled rejection when an asynchronous storage client is offline.
1804
+ }
1805
+ }
1806
+ validateAndHandleErrorByMessage(message) {
1807
+ const utf8ErrorMessage = 'Malformed UTF-8 data';
1808
+ if (message.includes(utf8ErrorMessage) ||
1809
+ message.toLowerCase().includes(utf8ErrorMessage.toLowerCase())) {
1810
+ this.writeUtf8Diagnostic(true);
1811
+ }
1812
+ }
1813
+ async pbkdf2WebCryptoHex(params) {
1814
+ const subtle = globalThis.crypto.subtle;
1815
+ const enc = new TextEncoder();
1816
+ const passBytes = enc.encode(params.password);
1817
+ const saltBytes = this.hexToBytes(params.saltHex);
1818
+ const keyMaterial = await subtle.importKey('raw', passBytes, { name: 'PBKDF2' }, false, ['deriveBits']);
1819
+ const bits = await subtle.deriveBits({
1820
+ name: 'PBKDF2',
1821
+ salt: saltBytes,
1822
+ iterations: params.iterations,
1823
+ hash: params.hash,
1824
+ }, keyMaterial, params.lengthBytes * 8);
1825
+ return this.bytesToHex(bits);
1826
+ }
1827
+ async encryptSHA512Async(password, salt) {
1828
+ if (this.hasWebCrypto()) {
1829
+ // Match CryptoJS PBKDF2 output format: hex string
1830
+ return await this.pbkdf2WebCryptoHex({
1831
+ password,
1832
+ saltHex: salt,
1833
+ iterations: this.getEncIterations(),
1834
+ lengthBytes: 32, // 256-bit
1835
+ hash: 'SHA-512',
1836
+ });
1837
+ }
1838
+ throw new Error('WebCrypto is required for vault key derivation');
1839
+ }
1840
+ async deriveLegacySessionKey(password, salt) {
1841
+ if (this.hasWebCrypto()) {
1842
+ return this.pbkdf2WebCryptoHex({
1843
+ password,
1844
+ saltHex: salt,
1845
+ iterations: 20000,
1846
+ lengthBytes: 32,
1847
+ hash: 'SHA-512',
1848
+ });
1849
+ }
1850
+ // Read compatibility only; new vault writes still require WebCrypto.
1851
+ return crypto_js_1.default.PBKDF2(password, crypto_js_1.default.enc.Hex.parse(salt), {
1852
+ keySize: 256 / 32,
1853
+ iterations: 20000,
1854
+ hasher: crypto_js_1.default.algo.SHA512,
1855
+ }).toString();
1856
+ }
1857
+ async deriveStoredSessionKey(password, vaultKeys) {
1858
+ if (vaultKeys.keyDerivation === LEGACY_ENCRYPTION_KDF) {
1859
+ return this.deriveLegacySessionKey(password, vaultKeys.salt);
1860
+ }
1861
+ if (vaultKeys.keyDerivation !== undefined) {
1862
+ throw new Error('Unsupported vault key derivation profile');
1863
+ }
1864
+ return this.encryptSHA512Async(password, vaultKeys.salt);
1865
+ }
1866
+ async _createTrezorAccount(coin, slip44, index, label) {
1867
+ const vault = this.getVault();
1868
+ const { accounts } = vault;
1869
+ // For EVM networks, Trezor expects 'eth' regardless of the network's currency
1870
+ const trezorCoin = slip44 === 60 ? 'eth' : coin;
1871
+ const { descriptor, balance: _balance } = await this.requireTrezorSigner().getAccountInfo({
1872
+ coin: trezorCoin,
1873
+ slip44,
1874
+ index,
1875
+ });
1876
+ const xpub = descriptor;
1877
+ const balance = _balance;
1878
+ let ethPubKey = '';
1879
+ const isEVM = (0, derivation_paths_1.isEvmCoin)(coin, slip44);
1880
+ // For EVM networks, we need to get the actual address from Trezor
1881
+ let address;
1882
+ if (isEVM) {
1883
+ // For EVM, the descriptor from getAccountInfo is the address
1884
+ address = xpub;
1885
+ // Get the public key for EVM
1886
+ const response = await this.requireTrezorSigner().getPublicKey({
1887
+ coin: trezorCoin,
1888
+ slip44,
1889
+ index: +index,
1890
+ });
1891
+ ethPubKey = response.publicKey;
1892
+ }
1893
+ else {
1894
+ // For UTXO, use the xpub to derive the address
1895
+ // Always use first receive address (index 0) for imported account display
1896
+ address = await this.getAddress(xpub, false, { forceIndex0: true });
1897
+ }
1898
+ if (this.accountAddressExists(accounts, address, isEVM))
1899
+ throw new Error('Account already exists on your Wallet.');
1900
+ if (!xpub || !address)
1901
+ throw new Error('Something wrong happened. Please, try again or report it');
1902
+ // Use getNextAccountId to properly handle placeholder accounts
1903
+ const id = this.getNextAccountId(accounts[types_1.KeyringAccountType.Trezor]);
1904
+ // Convert balance from satoshis to SYS safely
1905
+ // Using string manipulation to avoid precision loss
1906
+ let syscoinBalance = 0;
1907
+ if (!isEVM && balance) {
1908
+ const balanceStr = balance.toString();
1909
+ // Handle conversion without division to preserve precision
1910
+ if (balanceStr.length > 8) {
1911
+ // Has whole SYS part
1912
+ const wholePart = balanceStr.slice(0, -8);
1913
+ const decimalPart = balanceStr.slice(-8);
1914
+ syscoinBalance = parseFloat(`${wholePart}.${decimalPart}`);
1915
+ }
1916
+ else {
1917
+ // Less than 1 SYS
1918
+ const paddedBalance = balanceStr.padStart(8, '0');
1919
+ syscoinBalance = parseFloat(`0.${paddedBalance}`);
1920
+ }
1921
+ }
1922
+ const trezorAccount = {
1923
+ ...this.initialTrezorAccountState,
1924
+ balances: {
1925
+ syscoin: isEVM ? 0 : syscoinBalance,
1926
+ ethereum: 0,
1927
+ },
1928
+ address,
1929
+ label: label ? label : `Trezor ${id + 1}`,
1930
+ id,
1931
+ xprv: '',
1932
+ xpub: isEVM ? ethPubKey : xpub,
1933
+ assets: {
1934
+ syscoin: [],
1935
+ ethereum: [],
1936
+ },
1937
+ };
1938
+ return trezorAccount;
1939
+ }
1940
+ async _createLedgerAccount(coin, slip44, index, label) {
1941
+ const vault = this.getVault();
1942
+ const { accounts } = vault;
1943
+ let xpub;
1944
+ let address = '';
1945
+ if ((0, derivation_paths_1.isEvmCoin)(coin, slip44)) {
1946
+ const { address: ethAddress, publicKey } = await this.requireLedgerSigner().evm.getEvmAddressAndPubKey({
1947
+ accountIndex: index,
1948
+ });
1949
+ address = ethAddress;
1950
+ xpub = publicKey;
1951
+ }
1952
+ else {
1953
+ const ledgerXpub = await this.requireLedgerSigner().utxo.getXpub({
1954
+ index: index,
1955
+ coin,
1956
+ slip44,
1957
+ });
1958
+ // Convert device-returned extended key to BIP84 zpub/vpub for storage/backend usage
1959
+ const { types } = (0, sysweb3_network_1.getNetworkConfig)(slip44, coin);
1960
+ const bip84Target = slip44 === 1
1961
+ ? types.zPubType.testnet.vpub
1962
+ : types.zPubType.mainnet.zpub;
1963
+ xpub = (0, derivation_paths_1.convertExtendedKeyVersion)(ledgerXpub, bip84Target);
1964
+ // Always use first receive address (index 0) for imported account display
1965
+ address = await this.getAddress(xpub, false, { forceIndex0: true });
1966
+ }
1967
+ if (this.accountAddressExists(accounts, address, (0, derivation_paths_1.isEvmCoin)(coin, slip44)))
1968
+ throw new Error('Account already exists on your Wallet.');
1969
+ if (!xpub || !address)
1970
+ throw new Error('Something wrong happened. Please, try again or report it');
1971
+ // Use getNextAccountId to properly handle placeholder accounts
1972
+ const id = this.getNextAccountId(accounts[types_1.KeyringAccountType.Ledger]);
1973
+ const currentBalances = { syscoin: 0, ethereum: 0 };
1974
+ const ledgerAccount = {
1975
+ ...this.initialLedgerAccountState,
1976
+ balances: currentBalances,
1977
+ address,
1978
+ label: label ? label : `Ledger ${id + 1}`,
1979
+ id,
1980
+ xprv: '',
1981
+ xpub,
1982
+ assets: {
1983
+ syscoin: [],
1984
+ ethereum: [],
1985
+ },
1986
+ };
1987
+ return ledgerAccount;
1988
+ }
1989
+ // Common helper method for UTXO account creation
1990
+ async createUTXOAccountAtIndex(accountId, label) {
1991
+ try {
1992
+ // Create fresh signer just for this account creation operation
1993
+ const freshHDSigner = this.createOnDemandUTXOSigner(accountId);
1994
+ const sysAccount = await this.getFormattedBackendAccount({
1995
+ signer: freshHDSigner,
1996
+ });
1997
+ const encryptedXprv = this.getEncryptedXprv(freshHDSigner);
1998
+ // Generate network-aware label if none provided
1999
+ const vault = this.getVault();
2000
+ const network = vault.activeNetwork;
2001
+ const defaultLabel = this.generateNetworkAwareLabel(accountId, network);
2002
+ return {
2003
+ ...this.getInitialAccountData({
2004
+ label: label || defaultLabel,
2005
+ signer: freshHDSigner,
2006
+ sysAccount,
2007
+ xprv: encryptedXprv,
2008
+ }),
2009
+ balances: { syscoin: 0, ethereum: 0 },
2010
+ };
2011
+ }
2012
+ catch (error) {
2013
+ console.log('ERROR createUTXOAccountAtIndex', {
2014
+ error,
2015
+ });
2016
+ this.validateAndHandleErrorByMessage(error.message);
2017
+ throw error;
2018
+ }
2019
+ }
2020
+ async addNewAccountToSyscoinChain(label) {
2021
+ try {
2022
+ // Get next available account ID
2023
+ const vault = this.getVault();
2024
+ const accounts = vault.accounts[types_1.KeyringAccountType.HDAccount];
2025
+ const nextId = this.getNextAccountId(accounts);
2026
+ return await this.createUTXOAccountAtIndex(nextId, label);
2027
+ }
2028
+ catch (error) {
2029
+ console.log('ERROR addNewAccountToSyscoinChain', {
2030
+ error,
2031
+ });
2032
+ this.validateAndHandleErrorByMessage(error.message);
2033
+ throw error;
2034
+ }
2035
+ }
2036
+ async addNewAccountToEth(label) {
2037
+ try {
2038
+ // Get next available account ID
2039
+ const vault = this.getVault();
2040
+ const accounts = vault.accounts[types_1.KeyringAccountType.HDAccount];
2041
+ const nextId = this.getNextAccountId(accounts);
2042
+ // EVM accounts should use generic labels since they work across all EVM networks
2043
+ const defaultLabel = `Account ${nextId + 1}`;
2044
+ const newAccount = await this.setDerivedWeb3Accounts(nextId, label || defaultLabel);
2045
+ return newAccount;
2046
+ }
2047
+ catch (error) {
2048
+ console.log('ERROR addNewAccountToEth', {
2049
+ error,
2050
+ });
2051
+ this.validateAndHandleErrorByMessage(error.message);
2052
+ throw error;
2053
+ }
2054
+ }
2055
+ // Helper method to get next available account ID - fills gaps when accounts are deleted
2056
+ getNextAccountId(accounts) {
2057
+ const existingIds = Object.values(accounts)
2058
+ .filter((account) => {
2059
+ // Only count accounts that have been properly initialized
2060
+ // Placeholder accounts have empty addresses/xprv/xpub
2061
+ return account && account.address && account.xpub;
2062
+ })
2063
+ .map((account) => account.id)
2064
+ .filter((id) => !isNaN(id))
2065
+ .sort((a, b) => a - b); // Sort to find gaps efficiently
2066
+ if (existingIds.length === 0) {
2067
+ return 0;
2068
+ }
2069
+ // Find the first gap in the sequence
2070
+ for (let i = 0; i < existingIds.length; i++) {
2071
+ if (existingIds[i] !== i) {
2072
+ // Found a gap at position i
2073
+ return i;
2074
+ }
2075
+ }
2076
+ // No gaps found, return next sequential ID
2077
+ return existingIds.length;
2078
+ }
2079
+ async recreateSessionFromVault(saltedHashPassword) {
2080
+ try {
2081
+ // v4 vault is encrypted with the derived session password key (PBKDF2 output)
2082
+ // `saltedHashPassword` is the derived session password key passed by caller.
2083
+ const { mnemonic } = await this.vaultPersistence.getDecryptedVault(saltedHashPassword);
2084
+ if (!mnemonic) {
2085
+ throw new Error('Mnemonic not found in vault');
2086
+ }
2087
+ // Encrypt session data with sessionPassword hash for consistency
2088
+ // This allows keyring manager to decrypt with this.sessionPassword
2089
+ this.privateRecordSessionRevision++;
2090
+ this.sessionPassword = new SecureBuffer(saltedHashPassword);
2091
+ // Encrypt the mnemonic with session password for consistency with the rest of the code
2092
+ const encryptedMnemonic = crypto_js_1.default.AES.encrypt(mnemonic, saltedHashPassword).toString();
2093
+ this.sessionMnemonic = new SecureBuffer(encryptedMnemonic);
2094
+ console.log('[KeyringManager] Session data recreated from vault');
2095
+ }
2096
+ catch (error) {
2097
+ console.error('ERROR recreateSessionFromVault', { error });
2098
+ throw error;
2099
+ }
2100
+ }
2101
+ async _getPrivateKeyAccountInfos(privKey, label, options) {
2102
+ const vault = this.getVault();
2103
+ const { accounts } = vault;
2104
+ let importedAccountValue = null;
2105
+ const balances = {
2106
+ syscoin: 0,
2107
+ ethereum: 0,
2108
+ };
2109
+ // Try to validate as extended private key first
2110
+ const networkToUse = vault.activeNetwork;
2111
+ const zprvValidation = this.validateZprv(privKey, networkToUse);
2112
+ // Check if we're on an EVM network (slip44 = 60) or UTXO network
2113
+ const isEvmNetwork = networkToUse.slip44 === 60;
2114
+ if (zprvValidation.isValid) {
2115
+ // This is a valid UTXO extended private key
2116
+ if (isEvmNetwork) {
2117
+ throw new Error('Cannot import UTXO private key on EVM network. Please switch to a UTXO network (Bitcoin/Syscoin) first.');
2118
+ }
2119
+ const { node, network } = zprvValidation;
2120
+ if (!node || !network) {
2121
+ throw new Error('Failed to validate extended private key');
2122
+ }
2123
+ // Always use index 0 for consistency
2124
+ const nodeChild = node.derivePath(`0/0`);
2125
+ if (!nodeChild) {
2126
+ throw new Error('Failed to derive child node');
2127
+ }
2128
+ // Choose address type based on options or default to p2wpkh
2129
+ let addrObj;
2130
+ if (options?.utxoAddressType === 'p2pkh') {
2131
+ addrObj = bjs.payments.p2pkh({
2132
+ pubkey: nodeChild.publicKey,
2133
+ network,
2134
+ });
2135
+ }
2136
+ else if (options?.utxoAddressType === 'p2tr') {
2137
+ // For taproot, use x-only public key (32 bytes instead of 33)
2138
+ const xOnly = nodeChild.publicKey.length === 33
2139
+ ? nodeChild.publicKey.slice(1, 33)
2140
+ : nodeChild.publicKey;
2141
+ addrObj = bjs.payments.p2tr({
2142
+ internalPubkey: xOnly,
2143
+ network,
2144
+ });
2145
+ }
2146
+ else {
2147
+ // Default to SegWit (p2wpkh)
2148
+ addrObj = bjs.payments.p2wpkh({
2149
+ pubkey: nodeChild.publicKey,
2150
+ network,
2151
+ });
2152
+ }
2153
+ const { address } = addrObj;
2154
+ if (!address) {
2155
+ throw new Error('Failed to generate address');
2156
+ }
2157
+ importedAccountValue = {
2158
+ address,
2159
+ // IMPORTANT: Store BIP84 extended *public* key (zpub/vpub), not device-style xpub/tpub.
2160
+ // Blockbook derives different address branches depending on version bytes.
2161
+ // Using zpub/vpub ensures UTXO discovery and `input.path` match BIP84 (m/84'/slip44'/...),
2162
+ // which is required for HD signing.
2163
+ publicKey: (() => {
2164
+ try {
2165
+ const { types } = (0, sysweb3_network_1.getNetworkConfig)(networkToUse.slip44, networkToUse.currency || 'Bitcoin');
2166
+ const target = networkToUse.slip44 === 1
2167
+ ? types.zPubType.testnet.vpub
2168
+ : types.zPubType.mainnet.zpub;
2169
+ return (0, derivation_paths_1.convertExtendedKeyVersion)(node.neutered().toBase58(), target);
2170
+ }
2171
+ catch (_e) {
2172
+ // Fall back to the default neutered key if conversion fails.
2173
+ return node.neutered().toBase58();
2174
+ }
2175
+ })(),
2176
+ privateKey: privKey,
2177
+ };
2178
+ balances.syscoin = 0;
2179
+ }
2180
+ else {
2181
+ // If not a valid zprv/vprv, on UTXO networks try WIF
2182
+ const isEvmNetwork = networkToUse.slip44 === 60;
2183
+ let handledAsUtxo = false;
2184
+ if (!isEvmNetwork) {
2185
+ const wifValidation = this.validateWif(privKey, networkToUse);
2186
+ if (wifValidation.isValid) {
2187
+ // Create address from WIF and treat as single-address imported account
2188
+ const { networks } = (0, sysweb3_network_1.getNetworkConfig)(networkToUse.slip44, networkToUse.currency || 'Bitcoin');
2189
+ const isTestnet = networkToUse.slip44 === 1;
2190
+ const bitcoinNetwork = isTestnet
2191
+ ? networks.testnet
2192
+ : networks.mainnet;
2193
+ const keyPair = syscoinjs.utils.bitcoinjs.ECPair.fromWIF(privKey, bitcoinNetwork);
2194
+ // Choose address type based on options or default behavior
2195
+ let addrObj;
2196
+ if (options?.utxoAddressType === 'p2pkh') {
2197
+ addrObj = bjs.payments.p2pkh({
2198
+ pubkey: keyPair.publicKey,
2199
+ network: bitcoinNetwork,
2200
+ });
2201
+ }
2202
+ else if (options?.utxoAddressType === 'p2tr') {
2203
+ // For taproot, use x-only public key (32 bytes instead of 33)
2204
+ const xOnly = keyPair.publicKey.length === 33
2205
+ ? keyPair.publicKey.slice(1, 33)
2206
+ : keyPair.publicKey;
2207
+ addrObj = bjs.payments.p2tr({
2208
+ internalPubkey: xOnly,
2209
+ network: bitcoinNetwork,
2210
+ });
2211
+ }
2212
+ else {
2213
+ // Default to SegWit (p2wpkh)
2214
+ addrObj = bjs.payments.p2wpkh({
2215
+ pubkey: keyPair.publicKey,
2216
+ network: bitcoinNetwork,
2217
+ });
2218
+ }
2219
+ const address = addrObj.address;
2220
+ if (!address) {
2221
+ throw new Error('Failed to generate address from WIF');
2222
+ }
2223
+ importedAccountValue = {
2224
+ address,
2225
+ // For single-address WIF accounts, store xpub as the address marker
2226
+ publicKey: address,
2227
+ privateKey: privKey,
2228
+ };
2229
+ // Set UTXO balance bucket
2230
+ balances.syscoin = 0;
2231
+ handledAsUtxo = true;
2232
+ // Proceed to account creation below
2233
+ }
2234
+ else if (!isEvmNetwork && wifValidation.message) {
2235
+ // Provide useful feedback on UTXO network if WIF was attempted and failed
2236
+ // Continue to EVM handling only if actually EVM network
2237
+ }
2238
+ }
2239
+ // Check if the validation failed due to network mismatch
2240
+ if (zprvValidation.message &&
2241
+ zprvValidation.message.includes('Network mismatch')) {
2242
+ throw new Error(zprvValidation.message);
2243
+ }
2244
+ // Check if the validation failed due to invalid key prefix (only for known extended key formats)
2245
+ if (zprvValidation.message &&
2246
+ zprvValidation.message.includes('Invalid key prefix')) {
2247
+ throw new Error(zprvValidation.message);
2248
+ }
2249
+ // Check if it failed parsing as an extended key
2250
+ if (zprvValidation.message &&
2251
+ zprvValidation.message.includes('Failed to parse extended private key')) {
2252
+ throw new Error(zprvValidation.message);
2253
+ }
2254
+ // Check if it looks like an extended key that failed validation
2255
+ const knownExtendedKeyPrefixes = [
2256
+ 'xprv',
2257
+ 'xpub',
2258
+ 'yprv',
2259
+ 'ypub',
2260
+ 'zprv',
2261
+ 'zpub',
2262
+ 'tprv',
2263
+ 'tpub',
2264
+ 'uprv',
2265
+ 'upub',
2266
+ 'vprv',
2267
+ 'vpub',
2268
+ ];
2269
+ const prefix = privKey.substring(0, 4);
2270
+ const looksLikeExtendedKey = knownExtendedKeyPrefixes.includes(prefix);
2271
+ if (looksLikeExtendedKey) {
2272
+ // This looks like a UTXO extended key, but it failed validation
2273
+ // Don't try to import it as an EVM key
2274
+ if (isEvmNetwork) {
2275
+ throw new Error('Cannot import UTXO private key on EVM network. Please switch to a UTXO network (Bitcoin/Syscoin) first.');
2276
+ }
2277
+ // For UTXO networks, throw the original validation error
2278
+ throw new Error(zprvValidation.message || 'Invalid extended private key');
2279
+ }
2280
+ // If it's not an extended key and not a valid WIF, treat it as an Ethereum private key
2281
+ // But first check if we're on an EVM network
2282
+ if (!isEvmNetwork && !handledAsUtxo) {
2283
+ throw new Error('Cannot import EVM private key on UTXO network. Please switch to an EVM network first.');
2284
+ }
2285
+ if (!handledAsUtxo) {
2286
+ const hexPrivateKey = privKey.slice(0, 2) === '0x' ? privKey : `0x${privKey}`;
2287
+ // Validate it's a valid hex string (32 bytes = 64 hex chars)
2288
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hexPrivateKey) &&
2289
+ !/^[0-9a-fA-F]{64}$/.test(privKey)) {
2290
+ throw new Error('Invalid private key format. Expected 32-byte hex string or extended private key.');
2291
+ }
2292
+ importedAccountValue =
2293
+ this.ethereumTransaction.importAccount(hexPrivateKey);
2294
+ balances.ethereum = 0;
2295
+ }
2296
+ }
2297
+ if (!importedAccountValue) {
2298
+ throw new Error('Invalid private key format. Expected WIF, extended private key, or 32-byte hex.');
2299
+ }
2300
+ const { address, publicKey, privateKey } = importedAccountValue;
2301
+ // Validate duplicates across all account buckets, including passkey smart accounts.
2302
+ if (this.accountAddressExists(accounts, address, isEvmNetwork))
2303
+ throw new Error('Account already exists, try again with another Private Key.');
2304
+ const id = this.getNextAccountId(accounts[types_1.KeyringAccountType.Imported]);
2305
+ const defaultLabel = label || `Imported ${id + 1}`;
2306
+ return {
2307
+ ...initial_state_1.initialActiveImportedAccountState,
2308
+ address,
2309
+ label: defaultLabel,
2310
+ id,
2311
+ balances,
2312
+ isImported: true,
2313
+ xprv: this.withSecureData((sessionPwd) => {
2314
+ return crypto_js_1.default.AES.encrypt(privateKey, sessionPwd).toString();
2315
+ }),
2316
+ xpub: publicKey,
2317
+ assets: {
2318
+ syscoin: [],
2319
+ ethereum: [],
2320
+ },
2321
+ };
2322
+ }
2323
+ // NEW: On-demand signer creation methods
2324
+ /**
2325
+ * Common method to decrypt mnemonic from session
2326
+ * Eliminates code duplication across multiple methods
2327
+ */
2328
+ getDecryptedMnemonic() {
2329
+ if (!this.sessionMnemonic || !this.sessionPassword) {
2330
+ throw new Error('Session information not available');
2331
+ }
2332
+ const mnemonic = this.withSecureData((sessionPwd, sessionMnemonic) => {
2333
+ const decrypted = crypto_js_1.default.AES.decrypt(sessionMnemonic, sessionPwd).toString(crypto_js_1.default.enc.Utf8);
2334
+ if (!decrypted) {
2335
+ throw new Error('Failed to decrypt mnemonic');
2336
+ }
2337
+ return decrypted;
2338
+ });
2339
+ return mnemonic;
2340
+ }
2341
+ /**
2342
+ * Creates network RPC config from current active network without making RPC calls
2343
+ * Common utility for all on-demand signer creation
2344
+ */
2345
+ createNetworkRpcConfig() {
2346
+ const network = this.getVault().activeNetwork;
2347
+ return {
2348
+ formattedNetwork: network,
2349
+ networkConfig: (0, sysweb3_network_1.getNetworkConfig)(network.slip44, network.currency),
2350
+ };
2351
+ }
2352
+ /**
2353
+ * Common signer creation logic - takes decrypted mnemonic/zprv and creates fresh signer
2354
+ * OPTIMIZED: No RPC call needed - uses network config directly
2355
+ */
2356
+ createFreshUTXOSigner(mnemonicOrZprv, accountId) {
2357
+ // Create signer using network config directly (no RPC call)
2358
+ const rpcConfig = this.createNetworkRpcConfig();
2359
+ // Type assertion to match getSyscoinSigners expected interface
2360
+ const { hd } = (0, signers_1.getSyscoinSigners)({
2361
+ mnemonic: mnemonicOrZprv,
2362
+ rpc: rpcConfig,
2363
+ });
2364
+ // Create account at the specified index and set it as active
2365
+ // Note: createAccountAtIndex is synchronous despite TypeScript types
2366
+ hd.createAccountAtIndex(accountId, 84);
2367
+ // Verify the account was created correctly
2368
+ if (!hd.Signer.accounts.has(accountId)) {
2369
+ throw new Error(`Failed to create account at index ${accountId}`);
2370
+ }
2371
+ // Verify the correct account is active
2372
+ if (hd.Signer.accountIndex !== accountId) {
2373
+ throw new Error(`Account index mismatch: expected ${accountId}, got ${hd.Signer.accountIndex}`);
2374
+ }
2375
+ return hd;
2376
+ }
2377
+ /**
2378
+ * Creates a fresh UTXO signer for HD accounts derived from the main seed
2379
+ * OPTIMIZED: No RPC call needed - uses network config directly
2380
+ */
2381
+ createOnDemandUTXOSigner(accountId) {
2382
+ // Use common method to avoid code duplication
2383
+ const mnemonic = this.getDecryptedMnemonic();
2384
+ return this.createFreshUTXOSigner(mnemonic, accountId);
2385
+ }
2386
+ // NEW: Helper methods for HD signer management
2387
+ isZprv(key) {
2388
+ const zprvPrefixes = ['zprv', 'tprv', 'vprv', 'xprv'];
2389
+ return zprvPrefixes.some((prefix) => key.startsWith(prefix));
2390
+ }
2391
+ // Helper methods for secure buffer operations
2392
+ getSessionPasswordString() {
2393
+ if (!this.sessionPassword || this.sessionPassword.isCleared()) {
2394
+ throw new Error('Session password not available');
2395
+ }
2396
+ // WARNING: This exposes sensitive data as a string
2397
+ // Use only for CryptoJS operations that require string input
2398
+ return this.sessionPassword.toString();
2399
+ }
2400
+ getSessionMnemonicString() {
2401
+ if (!this.sessionMnemonic || this.sessionMnemonic.isCleared()) {
2402
+ throw new Error('Session mnemonic not available');
2403
+ }
2404
+ // WARNING: This exposes sensitive data as a string
2405
+ // Use only for CryptoJS operations that require string input
2406
+ return this.sessionMnemonic.toString();
2407
+ }
2408
+ // Secure method to perform cryptographic operations without exposing strings
2409
+ withSecureData(operation) {
2410
+ if (!this.sessionPassword || !this.sessionMnemonic) {
2411
+ throw new Error('Session data not available');
2412
+ }
2413
+ // Perform operation with minimal exposure
2414
+ const result = operation(this.getSessionPasswordString(), this.getSessionMnemonicString());
2415
+ // Clear any temporary variables if needed
2416
+ return result;
2417
+ }
2418
+ generateNetworkAwareLabel(accountId, network) {
2419
+ // Generate concise network-specific labels using actual network config
2420
+ const { label, chainId, kind, currency } = network;
2421
+ // Create a shortened network identifier based on actual network configurations
2422
+ let networkPrefix = '';
2423
+ if (kind === sysweb3_network_1.INetworkType.Syscoin) {
2424
+ // UTXO networks (slip44 = 57 for mainnet, 1 for testnet)
2425
+ if (chainId === 57) {
2426
+ networkPrefix = 'SYS'; // Syscoin UTXO Mainnet
2427
+ }
2428
+ else if (chainId === 5700) {
2429
+ networkPrefix = 'SYS-T'; // Syscoin UTXO Testnet (slip44=1)
2430
+ }
2431
+ else {
2432
+ // Other UTXO networks - use currency shortcut (e.g., "btc" -> "BTC")
2433
+ if (currency) {
2434
+ networkPrefix = currency.toUpperCase();
2435
+ }
2436
+ else {
2437
+ // Fallback to first word from label if no currency
2438
+ const firstWord = label.split(' ')[0];
2439
+ networkPrefix =
2440
+ firstWord.length > 6 ? firstWord.substring(0, 6) : firstWord;
2441
+ }
2442
+ }
2443
+ }
2444
+ else {
2445
+ // EVM networks (all use slip44=60)
2446
+ if (chainId === 1) {
2447
+ networkPrefix = 'ETH'; // Ethereum Mainnet
2448
+ }
2449
+ else if (chainId === 11155111) {
2450
+ networkPrefix = 'ETH-T'; // Ethereum Sepolia Testnet
2451
+ }
2452
+ else if (chainId === 137) {
2453
+ networkPrefix = 'POLY'; // Polygon Mainnet
2454
+ }
2455
+ else if (chainId === 80001) {
2456
+ networkPrefix = 'POLY-T'; // Polygon Mumbai Testnet
2457
+ }
2458
+ else if (chainId === 57) {
2459
+ networkPrefix = 'NEVM'; // Syscoin NEVM Mainnet
2460
+ }
2461
+ else if (chainId === 5700) {
2462
+ networkPrefix = 'NEVM-T'; // Syscoin NEVM Testnet
2463
+ }
2464
+ else if (chainId === 570) {
2465
+ networkPrefix = 'ROLLUX'; // Rollux Mainnet
2466
+ }
2467
+ else if (chainId === 57000) {
2468
+ networkPrefix = 'ROLLUX-T'; // Rollux Testnet
2469
+ }
2470
+ else {
2471
+ // Other EVM networks - use currency shortcut if available
2472
+ if (currency) {
2473
+ // Check if it's a testnet network
2474
+ if (label.toLowerCase().includes('testnet') ||
2475
+ label.toLowerCase().includes('test')) {
2476
+ networkPrefix = `${currency.toUpperCase()}-T`;
2477
+ }
2478
+ else {
2479
+ networkPrefix = currency.toUpperCase();
2480
+ }
2481
+ }
2482
+ else {
2483
+ // Fallback to extracting meaningful prefix from label
2484
+ const firstWord = label.split(' ')[0];
2485
+ if (firstWord.toLowerCase().includes('testnet') ||
2486
+ firstWord.toLowerCase().includes('test')) {
2487
+ const baseWord = label.split(' ')[0];
2488
+ networkPrefix = `${baseWord.substring(0, 4).toUpperCase()}-T`;
2489
+ }
2490
+ else {
2491
+ networkPrefix =
2492
+ firstWord.length > 6
2493
+ ? firstWord.substring(0, 6).toUpperCase()
2494
+ : firstWord.toUpperCase();
2495
+ }
2496
+ }
2497
+ }
2498
+ }
2499
+ return `${networkPrefix} ${accountId + 1}`;
2500
+ }
2501
+ /**
2502
+ * Clean up all resources
2503
+ */
2504
+ async destroy() {
2505
+ await this.lockWallet();
2506
+ // Clear any remaining references
2507
+ this.ethereumTransaction = {};
2508
+ this.syscoinTransaction = {};
2509
+ }
2510
+ }
2511
+ exports.KeyringCore = KeyringCore;
2512
+ //# sourceMappingURL=keyring-core.js.map