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